0

I use get_the_category_list to create a cat link in the header of my posts in the archive page, like so :

$categories_list = get_the_category_list( esc_html__( ', ', 'mytheme' ) );
if ( $categories_list ) {
    echo '<div class="cat-links">';
    get_template_part('images/inline', 'picto-actu.svg');
    $categories_list . '</div>';
}

I am trying to include the parent category to show it like so on the frontend : parent category > the category . But I'm probably not using the right method because whatever i try, i can't seem to get the parent, i can't even get the id of the child category from $categories_list, which would help me find the parent...

  • The last statement should be echo $categories_list . '</div>'; – Qaisar Feroz Mar 17 at 16:04
1

get_the_category_list() returns a formatted list of category names, which does not (as you discovered) include the IDs.

get_the_category(), by contrast, returns an array of WP Term objects. A WP Term object looks like this:

 ["term_id"]=>  //int
    ["name"]=>   //string 
    ["slug"]=>  //string 
    ["term_group"]=>  //int
    ["term_taxonomy_id"]=> //int
    ["taxonomy"]=>   //string
    ["description"]=>    //string
    ["parent"]=> //int
    ["count"]=>  // int
    ["filter"]= //string
    ["meta"]= array(0) {} //array

Source: https://developer.wordpress.org/reference/classes/wp_term/

As you can see, you can very easily pull out both the ID and the parent ID if present.

Once you have the parent ID, you can fetch its name with get_cat_name( $cat_id );

  • Works better now, thanks ! – Xavier C. Mar 17 at 16:36
1

Assuming that only one category is assigned to the post

$taxonomy = 'category';

// Get the term assigned to post.
$post_term = wp_get_object_terms( $post->ID, $taxonomy);

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

    // parent category object
    $parent = get_term($post_term[0]->parent, $taxonomy);

    echo '<div class="cat-links">';

    get_template_part('images/inline', 'picto-actu.svg');

    // Display post categories.
    echo '<a href="'. get_term_link($parent->term_id,$taxonomy).'">'.$parent->name.'</a> >';
    echo '<a href="'. get_term_link($post_term[0]->term_id,$taxonomy).'">'.$post_term[0]->name.'</a> >';

    echo '</div>';

}

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.