Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

This is the code I'm using to output the child categories of my posts as links.

<?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>';
        }
    }
}
?>

My questions is, how can I get it to only output one link, when the post is in more than one child category? I tried adding a break command after the last line, but that didn't work. Help appreciated.

share|improve this question
add comment

1 Answer

up vote 0 down vote accepted

You need to break both foreach loops not just one, so add break 2; after the echo.

   $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>';
                break 2;
            }
        }
    }
share|improve this answer
    
You're a genius, thank you. –  user34277 Jun 25 '13 at 23:56
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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