WordPress.org

Ready to get started?Download WordPress

Forums

Output one child category OR another (3 posts)

  1. CharlieLivingston
    Member
    Posted 1 year ago #

    So I'm fed up of taking my site down by trying to do this myself. I'm using this snippet:

    <?php
    
    foreach((get_the_category()) as $childcat) {
    
    if (cat_is_ancestor_of(106, $childcat)) {
    
    echo '<a href="'.get_category_link($childcat->cat_ID).'">';
    
     echo $childcat->cat_name . '</a>';
    
     break;
    }}
    
    ?>

    to output a child category as a link. The parent category is 106. If the post is in a child category of that parent category, it outputs the child category as a link. But I want to make code also display the link if the post is in a child category of parent category 107.

    I tried this code:

    <?php
    
    foreach((get_the_category()) as $childcat) {
    
    if (cat_is_ancestor_of(106, $childcat) or (cat_is_ancestor_of(107, $childcat)) {
    
    echo '<a href="'.get_category_link($childcat->cat_ID).'">';
    
     echo $childcat->cat_name . '</a>';
    
     break;
    }}
    
    ?>

    But got an error message. I've tried other things too, but none of them work. I'm sure this is really simple for someone who knows a bit of PHP.

    Here's the relevant bit of the codex: http://codex.wordpress.org/Function_Reference/cat_is_ancestor_of

  2. linux4me2
    Member
    Posted 1 year ago #

    It looks like you've just got the wrong number of parentheses in your code.

    If you want to use your version of the code, try this:

    <?php
    
    foreach(get_the_category() as $childcat) {
    	if ((cat_is_ancestor_of(106, $childcat)) or ((cat_is_ancestor_of(107, $childcat))) {
    		echo '<a href="'.get_category_link($childcat->cat_ID).'">' . $childcat->cat_name . '</a>';
    	}
    }
    ?>

    Or if you think you might want to use more than two categories in the future, put the values of the parent category in an array:

    <?php
    $mycats = array(106, 107);
    foreach (get_the_category() as $childcat) {
    	foreach ($mycats as $mycat) {
    		if (cat_is_ancestor_of($mycat, $childcat)) {
    			echo '<a href="'.get_category_link($childcat->cat_ID).'">' . $childcat->cat_name . '</a>';
    		}
    	}
    }
    ?>
  3. CharlieLivingston
    Member
    Posted 1 year ago #

    That's brilliant, thank you. I'm using the array version and it works perfectly. Except for one thing. I only want it to display one child category, even if the post is in more than one. So before I used a break command to achieve this. I tried adding a break after the echo line in your code but it's still outputting multiple child categories. You can see the problem here. Under the latest themes you get child categories joined together like 'EcommercePortfolio'. I'd rather it just said 'Ecommerce' or just 'Portfolio'.

    Help appreciated.

Topic Closed

This topic has been closed to new replies.

About this Topic