Grouping Parent and child categories for post and

2019-09-14 07:38发布

问题:

I have seen a few questions for how to display parent and child categories but can't seem to find a solution for what I am doing.

I'm using the default wordpress post with several categories and child categories for an example I have

News - Travel - World - Business

Article -General

Case Study -Thomas Cook - Easy Jet

The post can have any number of categories but what I am looking to do is group the child with its parent so that when I display a post it, for example, displays the Parent and Child categories used for each post in the following format (colon after the parent and hyphen after each child apart from the last).

News: Travel - World

Currently I am using the following code;

<?php 
$categories = get_the_category();
$separator = ' - ';
$output = '';
if ( ! empty( $categories ) ) {
    foreach( $categories as $category ) {
        $output .= '<a class="blog-panel-cat" href="' . esc_url( get_category_link( $category->term_id ) ) . '" alt="' . esc_attr( sprintf( __( 'View all posts in %s', 'textdomain' ), $category->name ) ) . '">' . esc_html( $category->name ) . '</a>' . $separator;
    }
    echo trim( $output );
}
?>

But his just outputs one category after the other with no way of grouping so I can add ':' after the parent and separate the child for that parent with '-' and also a double space before the next parent.

Any help appreciated

Thanks

Ian

回答1:

I've worked on the exact same case a few months ago and here is my solution

//first  part
$allcats = get_the_category();
$parent_id = $all_ids = array();

foreach ($allcats as $cats) {
    //get all category id first
    $all_ids[] = $cats->term_id;

    // get top parent category
    if ($cats->category_parent === 0 ) {
        $parent_id[] =  $cats->term_id;
    }
}

//second part
$separator = ' &raquo; ';
$term_ids = implode( ',' , $all_ids );

$post_categories  = '';
foreach ($parent_id as $parents) {
    $parent_name    = get_cat_name($parents);
    $parent_link    = get_category_link($parents);
    $parent_cat     = '<span class="parent"><a href="'.$parent_link.'">'.$parent_name.'</a></span>';

    //get all sub category with certain ids
    $child_cats = wp_list_categories(
        array(
        'child_of' =>  $parents, 
        'title_li' => '',
        'style'    => 'none',
        'echo'     => false,
        'taxonomy' => 'category',
        'include'  => $term_ids,

        )
    );
    $child_cats = rtrim( trim( str_replace( '<br />',  $separator, $child_cats ) ), $separator );
    $hcat .= '<b>'.$parent_cat.'</b> &raquo; '.$child_cats.'<br>';
}

echo $post_categories;

Tested and hope this help.



回答2:

I have done something similar for showing in Rest Api, so all this does is arranges all of the categories into hierarchical arrays/objects. And it only works for first-grade children.

$allcats = get_categories(); // get ALL categories 
// $allcats = get_the_category(); // get only categories assigned to post
$parents = $all_ids = array();

//  find parents
foreach ($allcats as $cats) {
    if ($cats->category_parent === 0 ) {
        $cats->children = array();
        $parents[] =  $cats;
    }
}

//  find childredn and assign it to corresponding parrent  
foreach ($allcats as $cats) {
    if ($cats->category_parent != 0) {
        foreach ($parents as $parent) {
            if ($cats->category_parent === $parent->term_id) {
                $parent->children[] = $cats;
            }
        }
    }
}

So the result will be something like:

[{
   term_id: 50,
   name: "Main Cat",
   slug: "main-cat",
   term_group: 0,
   term_taxonomy_id: 50,
   taxonomy: "category",
   description: "",
   parent: 0,
   count: 77,
   filter: "raw",
   term_order: "1",
   cat_ID: 50,
   category_count: 77,
   category_description: "",
   cat_name: "main cat",
   category_nicename: "main_cat",
   category_parent: 0,
   children: [
   {
      term_id: 49,
      name: "Sub Cat",
      slug: "sub-cat",
      term_group: 0,
      term_taxonomy_id: 49,
      taxonomy: "category",
      description: "",
      parent: 50,
      count: 43,
      filter: "raw",
      term_order: "1",
      cat_ID: 49,
      category_count: 43,
      category_description: "",
      cat_name: "sub_cat",
      category_nicename: "Sub Cat",
      category_parent: 50
    }, 
    {etc other children}
   ]
 }]

Hope this helps someone...



标签: php wordpress