WordPress.org

Support

Support » How-To and Troubleshooting » Using get_the_category() for formatting

Using get_the_category() for formatting

  • I want to change the look of my posts depending on the category that they fall under. The code down below is supposed to go through all of the categories of a post, determine whether or not it falls under one or two specific categories, and then echo the appropriate html. I’m still new to PHP so I don’t know the exact syntax. Can you take a look at this and tell me what I’m doing wrong? Also, is this the optimal way to do it? If not, can you give me some pointers?

    Thanks

    <?php
    
    var cat1 = false;
    var cat2 = false;
    
    foreach( ( get_the_category() ) as $category )
    {
        if ( $category->cat_name == "category1" )
        {
            cat1 = true;
        }
        else if ( $category->cat_name == "category2" )
        {
            cat2 = true;
        }
    }
    
    if ( cat1 && cat2 )
        echo '<div class="both">';
    else if ( !cat1 && !cat2 )
        echo '<div class="none">';
    else if ( cat1 )
        echo '<div class="cat1">';
    else
        echo '<div class="cat2">';
    
    ?>
Viewing 2 replies - 1 through 2 (of 2 total)
  • esmi

    @esmi

    Forum Moderator

    You might want to use in_category instead of $category->cat_name == "category1".

    Try using this:

    <?php
    
    $cat1 = false;
    $cat2 = false;
    
    foreach( ( get_the_category() ) as $category )
    {
        if ( $category->cat_name == "category1" )
        {
            $cat1 = true;
        }
        elseif ( $category->cat_name == "category2" )
        {
            $cat2 = true;
        }
    }
    
    if ( $cat1 && $cat2 )
        echo '<div class="both">';
    elseif ( !$cat1 && !$cat2 )
        echo '<div class="none">';
    elseif ( $cat1 )
        echo '<div class="cat1">';
    else
        echo '<div class="cat2">';
    
    ?>
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Using get_the_category() for formatting’ is closed to new replies.
Skip to toolbar