w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Get Wordpress child category from specific parent

So now I'm fetching a list of category and its child, then I fetch posts having parent category assigned to it, after I get posts array, I loop into it and get all the categories assigned to the post, If there are additional categories other than the required category and its child I skip the post, otherwise do whatever I want to do.

$category = get_category_by_slug( 'category-name' );

$args = array(
'type'                     => 'post',
'child_of'                 => $category->term_id,
'orderby'                  => 'name',
'order'                    => 'ASC',
'hide_empty'               => FALSE,
'hierarchical'             => 1,
'taxonomy'                 => 'category',
); 
$child_categories = get_categories($args );

$category_list = array();
$category_list[] = $category->term_id;

if ( !empty ( $child_categories ) ){
    foreach ( $child_categories as $child_category ){
        $category_list[] = $child_category->term_id;
    }
}

$posts_args = array(
'posts_per_page'   => 10,
'cat'  => $category->term_id,
'post_type'        => 'post',
'post_status'      => 'publish',
'suppress_filters' => true 
);

$posts = new WP_Query ( $posts_args );
if ( $posts->have_posts() ){

  while ( $posts->have_posts() ){
    $posts->the_post(); 
    $category_array = array();
    $post_categories = get_the_category ( get_the_ID() );
    if ( !empty ( $post_categories ) ){
       foreach ( $post_categories as $post_category ) {
          $category_array[] = $post_category->term_id;
        }
    }
    //Checks if post has an additional category
    $result = array_diff( $category_array,  $category_list   ); 

    if ( empty ( $result ) ) { ?>
       <li>
         <a href="<?php the_permalink(); ?>" class="side-thumb"
title="<?php the_title(); ?>"> dfdf<?php 
             if ( has_post_thumbnail() ){
                 echo get_the_post_thumbnail();
             } 
             //Put your default icon code here 
             ?>
         </a> 
        </li> <?php
     }
   }
  }
  wp_reset_postdata();

Above answer is as per your explanation, but I think what you want is, like you have a category Artists and there are subcategories each having a specific name, So for Artist gallery you want to display list of all the artists with their pictures.





© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.