0
votes

Either this is harder than it needs to be or I am just not understanding WordPress/PHP very well :( All I want to do is show the child/sub categories of a specific parent category...but only if the post is in those subcategories. Specific example:

I am building a wine reviews website and these are the categories:

  • Brand
    • Subcategory 1
    • Subcategory 2
    • etc.
  • Region
    • Subcategory 1
    • Subcategory 2
    • etc.
  • Grape
    • Subcategory 1
    • Subcategory 2
    • etc.

The parent categories will never change, and every post will have at least 1 subcategory selected under each parent, so in the LOOP I can just list the parents by name. But I am needing to dynamically output the subcategories, something like this:

Brand: <?php list_post_subcategories('brand'); ?>
Region: <?php list_post_subcategories('region'); ?>
Grape: <?php list_post_subcategories('grape'); ?>

Is there any easy way like this? It seems like this should be a basic function in Wordpress? I've looked at the functions 'get_categories' and 'in_category' but they don't seem to be able to do this.

3

3 Answers

0
votes
<?php $post_child_cat = array();
foreach((get_the_category()) as $cats) {
    $args = array( 'child_of' => $cats->cat_ID );
    $categories = get_categories( $args );
    if( $categories ) foreach( $categories as $category ) {
    echo $category->cat_name; }
} ?>

try this

0
votes

I posted to Wordpress Answers to get more help and @Milo gave a great code solution:

// get top level terms
$parents = get_terms( 'category', array( 'parent' => 0 ) );
// get post categories
$categories = get_the_terms( $post->ID, 'category' );
// output top level cats and their children
foreach( $parents as $parent ):
// output parent name and link
echo '<a href="' . get_term_link( $parent ) . '">' . $parent->name . '</a>: ';
// initialize array to hold child links
$links = array();
foreach( $categories as $category ):
    if( $parent->term_id == $category->parent ):
        // put link in array
        $links[] = '<a href="' . get_term_link( $category ) . '">' . $category->name .      '</a>';
    endif;
endforeach;
// join and output links with separator
echo join( ', ', $links );
endforeach;
0
votes

You can use array_map so you can return only the categories that you want. For example:

array_map( function( $cat ) {
        if ( $cat->parent != 0 ) {
            return $cat;
        }
     },
     get_the_category()
);