I have written this script to list the neighborhood associated with a post:

<div class="neighborhood">What&#39;s Happening in:<?php
foreach((get_the_category()) as $childcat) {
  if (cat_is_ancestor_of(12, $childcat)) {
    echo '<a href="'.get_category_link($childcat->cat_ID).'">';
    echo $childcat->cat_name . '</a>';

It works great. But I need to rewrite this to be an if / else statement, in the event that there is no neighborhood assigned to a post that the "What's Happening In" part would not appear.

My PHP isn't super strong, and I'm not sure how to restructure the code so that it is an effective if / else. Any help is appreciated.


See the comments in code for explaination

// all the categories for the post
$categories = get_the_category();

// extracts ids form post categories
$categories_ids = wp_list_pluck( $categories, 'term_id' );

// all the categories id that are descendant of category 12
$children = get_terms('category', array('child_of'=>12, 'fields'=>'ids') );

// all the categories id for the post that are descendant of category 12
$neighborhood = array_intersect($categories_ids, $children);

// show the div only if we have neighborhood 
if ( ! empty($neighborhood) ) {
  echo '<div class="neighborhood">What&#39;s Happening in:';
  foreach ( $categories as $cat ) {
    if ( ! in_array($cat->term_id, $neighborhood) ) continue;
    echo '<a href="'. get_category_link($cat->term_id) . '">' . $cat->name . '</a>';
  echo '</div>';

More on:

| improve this answer | |

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.