• I’m trying to create a simply breadcrumb for a custom post type, whereby only a single parent and child category can be assigned to a single post, in the hope that the result is:

    Help Centre > Parent > Child

    There are four parent categories and several child categories in each parent.

    I am using the following:

    $terms = get_the_terms($post->ID, 'help-centre-category');
    
    echo '<ul class="breadcrumb">';
    	echo '<li><a href="'.get_site_url().'/help-centre/">Help Centre</a></li>';
    	echo '<li><a href="'.get_site_url().'/help-centre/'.$terms[0]->slug.'/">'.$terms[0]->name.'</a></li>';
    	echo '<li><a href="'.get_site_url().'/help-centre/'.$terms[0]->slug.'/'.$terms[1]->slug.'/">'.$terms[1]->name.'</a></li>';
    echo '</ul>';

    My understanding was that $terms[0] was the parent and $terms[1] was the child, however this only seems to be the case for posts in two of the four parent categories, whilst the other two parent categories are generating the breadcrumb backwards, ie:

    Help Centre > Child > Parent.

    Am I approaching this incorrectly?

Viewing 1 replies (of 1 total)
  • Thread Starter JFK1980

    (@jfk1980)

    Well, I managed to get it working, although not sure it’s the most elegant solution:

    $terms = get_the_terms($post->ID, 'help-centre-category');
    
    foreach ($terms as $term) {
    	if ($term->parent == 0) {
    		echo '<li><a href="'.get_site_url().'/help-centre/'.$term->slug.'/">'.$term->name.'</a></li>';
    	}
    }
    foreach ($terms as $term) {
    	if ($term->parent != 0) {
    		echo '<li><a href="'.get_site_url().'/help-centre/'.$term->slug.'/'.$term->slug.'/">'.$term->name.'</a></li>';
    	}
    	//Prevent more than one child showing if accidentally selected
    	break;
    }

    Any thoughts on how to improve it would be appreciated.

    Thanks

Viewing 1 replies (of 1 total)
  • The topic ‘Issue with get_the_terms() and custom taxonomies.’ is closed to new replies.