-1

Not sure why this seemingly elementary function is so difficult to perform, but I've spent a lot of time scouring the web, incorporating the suggestions and not getting the intended output.

On the single post template I would like to display the categories like this:

Parent, Child, Child

If there are no children, it will just be:

Parent

I would also like the option to remove the href. Currently I have:

<?php
  $cat = get_the_category();
  $allCats = $cat[0]->cat_ID;
  echo get_category_parents( $allCats, false, ',' ); 
?>

This doesn't work in two ways:

1) It's missing one of my 3 categories

2) It's adding a comma after the last category (there should be 3rd a category here)

The standard code:

 <?php the_category(', ')?>

prints all three categories, but I don't have the option to strip the href, and they are in this incorrect order:

Child,Parent,Child

I'm guessing there will be a super simple way to do this but it's not super simple to find online! Any help appreciated :)

  • Anonymous markdowns are so useful, well done! – Doughballs Mar 21 at 14:28
0

Here is code snippet from WordPress that display the categories (or terms from other taxonomies) assigned to a post ordered by parent-child category relationship.This example must be used inside the loop.

$taxonomy = 'category';

// Get the term IDs assigned to post.
$post_terms = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) );

// Separator between links.
$separator = ', ';

if ( ! empty( $post_terms ) && ! is_wp_error( $post_terms ) ) {

    $term_ids = implode( ',' , $post_terms );

    $terms = wp_list_categories( array(
        'title_li' => '',
        'style'    => 'none',
        'echo'     => false,
        'taxonomy' => $taxonomy,
        'include'  => $term_ids
    ) );

    $terms = rtrim( trim( str_replace( '<br />',  $separator, $terms ) ), $separator );

    // Display post categories.
    echo  $terms;
}

Information on this page may help you to adjust the code to your requirements. I hope this will help.

  • Thanks - this has provided the correct sorting (Parent, Child, Child), but there is still no space after the comma and they are links. I will check the link you posted to fine tune. It still seems crazy to me that it takes so many lines of code to do a fairly elementary task. Parent > Child sorting should be straight out of the box IMO. – Doughballs Feb 25 at 14:49

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.