0

This is my previous question Wrap a chosen category name with div which I made a mistake on the question, however I got the correct answer. But thats not what I needed.

Currently, I'm using this code to get the category list for a single post.

<div>
    <?php $categories_list = get_the_category_list(__(' , ', 'theme')); ?>
    <?php printf(__('%1$s', 'xBlog'), $categories_list); ?> 
</div>

which outputs :

foo, foo1, foo2, foo3, foo4

How do I wrap foo1 in a div? so I can only style that particular category name.

First Attempt

    <?php $categories_list = get_the_category_list(__(' / ', 'theme')); 
    $category_name = 'foo1';
    if($categories_list){
    foreach($categories_list as $category) 
    {
        if ( $category_name == $category->cat_name) 
       {
              $output .='<div class="category-custom-class">'.$category->cat_name.'</div>';
       }
       else
       {
             $output .='<div class="category-custom-class1">'.$category->cat_name.'</div>';
       }
}
    }
    ?>
    <?php printf(__(' %1$s', 'theme'), $categories_list); ?>

Getting Error

Invalid argument supplied for foreach()

  • get_the_category_list() returns a string, not an array, that is why you get the error. Try using wp_get_post_terms() or get_the_category() – Pieter Goosen Apr 27 '15 at 13:27
1

You can try looping to match the category name you need.

$categories = get_the_category();
$category_name = 'foo1'; // set this to the category name you want to show
$output = '';
if($categories){
foreach($categories as $category) 
{
        if ( $category_name == $category->cat_name) 
       {
              $output .='<div class="category-custom-class">'.$category->cat_name.'</div>';
       }
       else
       {
             $output .='<div class="category-custom-class1">'.$category->cat_name.'</div>';
       }
}
echo $output;
}
  • Thanks for your answer. However, the category order may change in the future. I don't think this is a good solution. – KC Chai Apr 27 '15 at 11:37
  • Code is updated now. Please check if this is what you needed. – Manoj Kumar Apr 27 '15 at 12:02
  • Please check my edits, I'm getting error "Invalid argument supplied for foreach()" I still have no idea how this works. – KC Chai Apr 27 '15 at 13:06
  • This will not work, get_the_category_list returns a string, not an array – Pieter Goosen Apr 27 '15 at 13:20
  • Try using get_the_category and update the results. @DroidBeginner – Manoj Kumar Apr 27 '15 at 14:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.