Using if/else statements with output from theme options

In another question I was talking about using theme options to modify CSS. This is a separate but related question.

When a user sets a link colour in my theme, here’s how I’m including their choice:

Read More
<?php $options = get_option('mytheme_theme_options'); _e( 'a, a:link {color: #' ); echo $options['linkcolour']; _e( ';}' ); ?>

So, if a user specifies a link colour of #333333 in the theme options page, then my code above outputs a nice clean bit of CSS:

a, a:link {color: #333333;}

Great.

However, if they don’t specify any link colour value, then I get this:

a, a:link {color: #;}

…which is both ugly and redundant — it doesn’t do anything.

I’m not a PHP person, so I don’t really know the best way to fix this, but I imagine that it could be fixed with an if-else statement of some kind, where the code only gets output when the user sets a value. Is that right? If so, what code should I use?

Thanks.

Related posts

Leave a Reply

1 comment

  1. There’s no need to be using _e() that’s for text that’s to be translated, you don’t translate CSS, it only comes in one language…

    With regard to your if/else’ing, try this..

    <?php 
    $options = get_option('mytheme_theme_options');
    if( isset( $options['linkcolour'] ) && ( !empty( $options['linkcolour'] ) ) )   
        printf( "a, a:link {color: #%s;}", $options['linkcolour'] );
    ?>
    

    Here’s some PHP references for helping understand the PHP that was used above.

    http://www.php.net/manual/en/control-structures.if.php
    http://php.net/manual/en/function.isset.php
    http://www.php.net/manual/en/function.empty.php
    http://php.net/manual/en/function.printf.php

    Hope that helps.