• <?php foreach((get_the_category()) as $childcat)
    { if (cat_is_ancestor_of(18, $childcat))
    {echo $childcat->cat_name; }
    else
    {echo "No";}
    } ?>

    Basically I want to test for the parent category of ID 18, any of its child categories are selected, if yes echo the name of child category, if no echo No.

    When the child category is selected it’s fine- the child category is echoed. But when the child catgory is not selected, the echo is NoNo. Double output is produced by the code.

    Is there anything wrong with the code above? Thank you.

Viewing 2 replies - 1 through 2 (of 2 total)
  • Moderator Steven Stern (sterndata)

    (@sterndata)

    Volunteer Forum Moderator

    If there are two results for the foreach loop then you could get “no no”.

    try changing the else condition to

    else {
          echo "<pre>"; print_r($childcat); echo "</pre>";
          echo "no";
          }

    so you can see that you’re getting from get_the_category

    Thread Starter hungzai

    (@hungzai)

    Thanks sterndata but still don’t work.

    I got double string because it was also in another child category under the same parent category. Hence both categories pass through the function and hence I get double string output.

    Basically what i wanted to achieve is this.

    2 child categories(Apples and Orange) under Fruits(parent category).
    I want to display it in a column displaying the name Apple if it under Apple category and ‘no’ if it is not. Also for the Orange column, Display Orange if it is in Orange and no if not. Well there are child categories. Problem with this now is both if some other child categories are selected for eg, banana or pineapples are ticked as well, then all of those will pass through and produce a no. Which menas if I ticked 4 child category, there will be no no no no.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Echo produces double output of string.’ is closed to new replies.