WordPress.org

Ready to get started?Download WordPress

Forums

Using get_the_category() for formatting (3 posts)

  1. darthjones
    Member
    Posted 4 years ago #

    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">';
    
    ?>
  2. esmi
    Forum Moderator
    Posted 4 years ago #

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

  3. vtxyzzy
    Member
    Posted 4 years ago #

    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">';
    
    ?>

Topic Closed

This topic has been closed to new replies.

About this Topic