skip to Main Content

Is it possible to only show the code below if there’s a category description?

<h2>About <?php $cat = get_the_category(); echo $cat[0]->cat_name; ?></h2>

<?php $catID = get_the_category(); echo category_description ( $catID[0] ); ?>

I have these codes on my single posts in WordPress but sometimes, I forgot to add descriptions on a new category that I added. So when a user visits the post, they will just see the word About Category and no description at all, making it looks like an incomplete article.

I’m not a developer and I’m also not familiar with PHP. I only added that code on the single.php to show the description. But I want it not to show when there’s no description available.

Hope someone can give me the exact code to make it work.

Thanks!

2

Answers


  1. <?php if ($cat = get_the_category() && count($cat)>0) { ?>
        <!-- <?php echo print_r($cat,1); ?> -->
       <h2>About <?php echo $cat[0]->cat_name;?></h2>
       <?php echo category_description ($cat[0]->cat_id); ?>
    <?php } ?>
    
    Login or Signup to reply.
  2. Good practice to assign your values into variables at the top of your script before entering into HTML whenever possible. This will help prevent you making redundant calls and to debug your code better. Once you have your assigned values, you’ll want to check if the value is empty. I am assuming the code you presented will always return some kind of value for index 0.

    <?php
        $cat        = get_the_category();
        $cat_0      = $cat[0];
        $cat_0_name = $cat_0->cat_name;
        $cat_0_desc = category_description($cat_0);
    ?>
    
    <?php if(!empty($cat_0_desc)): ?>
        <h2>About <?php echo $cat_0_name; ?></h2>
        <?php echo $cat_0_desc; ?>
    <?php endif; ?>
    

    I should like to point out that I am choosing to use an alternative syntax for control structures versus the traditional brace control. This will make your code more readable and easily debugged when mixed in with HTML.

    If your code is still throwing you errors, I would suggest you check your error logs as something would be happining during the get_the_cateory() call or that it’s not returning any values resulting in error with $cat[0].

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search