• Charlie L

    (@charlielivingston)


    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

Viewing 1 replies (of 1 total)
  • 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>';
    		}
    	}
    }
    ?>

Viewing 1 replies (of 1 total)
  • The topic ‘Output one child category OR another’ is closed to new replies.