0

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.

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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