简体   繁体   中英

How to display post in WordPress based on parent category?

This is my structure:

+Parent Cat
  -Child Cat 1
  -Child Cat 2
  -Child Cat 3

I want to display all posts, that are in the parent and child categories.

With priority to display posts that are sticky.

This is my code:

 global $post; $category = get_the_category($post->ID); $category = $category[0]->cat_ID; $myposts = get_posts( array( 'posts_per_page'=>20, 'offset' => 0, 'cat' => $category, 'post_status'=>'publish', 'order'=>'ASC', 'ignore_sticky_posts' => 0 ), );

But this code only displays posts that are in the child category not Parent category. And the priority of sticky posts is not respected.

This is because

  1. get_the_category only returns the categories that are assigned to that post - and it looks like you are specifically limiting it to the first category.
  2. cat doesn't traverse upward to parent categories. It does return posts of child categories.

To do what you want, get the parent property from the category object:

global $post;
    $category = get_the_category($post->ID);
    $category = $category[0]->cat_ID;
    // category parent
    $category_parent = $category[0]->parent; 
    // Build the category array 
    $category_array = [ $category, $category_parent ];
   
    
    $myposts = get_posts(
        array(
                'posts_per_page'=>20,
                'offset' => 0,
                'category__in' => $category_array, // set the array here.
                'post_status'=>'publish',
                'order'=>'ASC',
        ),
    );

You can remove ignore_sticky_posts since the default value is already false, can you can use category__in instead of cat to pass an array of categories.

This is untested, but should work. If it doesn't, try doing:

`'cat' => implode(',', $category_array )`

Instead of the category__in .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM