Need help with else if statement

I am trying to set up my blog so that there are different colors for 2 different categories, however, if there is a post that is tagged with neither of these 2 categories I want it to default to green.

Here is my code:

Read More
    <?php if ( in_category( 'News' )) : ?>
    <div class="green">
    <?php elseif ( in_category('Blog')) : ?>
    <div class="orange">
    <?php endif; ?>  

So basically I want to change it so that if the post isn’t in the “News” or the “Blog” category, it will just default to the “green” class.

Thanks in advance!

Related posts

2 comments

  1. You should familiarize yourself with PHP, but if you want a default color ( assuming the code below already works ) you could do:

    <?php if ( in_category( 'News' )) : ?>
        <div class="green">
    <?php elseif ( in_category('Blog')) : ?>
        <div class="orange">
    <?php else : ?>
        <div class="pink">
    <?php endif; ?>
    
  2. I’d suggest you use post_class for this. The following goes into your functions.php:

    function category_name_post_class( $classes ) {
        global $post;
            $categories = get_the_category( $post->ID );
        foreach( $categories as $category)
            $classes[] = $category->category_nicename;
            return $classes;
    }
    add_filter('post_class', 'category_name_post_class');
    

    Your div now looks like this:

    <div <?php post_class(); ?>>
    

    which output some thing like:

    <div class="your-category-name">
    

    the styling is done via CSS as always.

Comments are closed.