wp query - How to get the latest post list (of the parent custom custom type)

admin2025-04-21  0

I am looking for a solution to get the latest list of custom parent posts.

example:

Post A

Child Post A

Child Post B

Child Post C

The bold list items are the posts/pages I want to retrieve.

I want to take the last post: Child Post C

And finally, I want to get the list of the last posts of the parent category to display on the home page

example: I have the list as the image below.

I want to display in the loop in the home page

I want to display the last post in the list, only the last post.

example:

1.Child Post A 3

2.Child Post B 3

Thanks for all the help / I used google translate tool to describe :D

I am looking for a solution to get the latest list of custom parent posts.

example:

Post A

Child Post A

Child Post B

Child Post C

The bold list items are the posts/pages I want to retrieve.

I want to take the last post: Child Post C

And finally, I want to get the list of the last posts of the parent category to display on the home page

example: I have the list as the image below.

I want to display in the loop in the home page

I want to display the last post in the list, only the last post.

example:

1.Child Post A 3

2.Child Post B 3

Thanks for all the help / I used google translate tool to describe :D

Share Improve this question asked Sep 7, 2019 at 18:05 Maria OzawaMaria Ozawa 1
Add a comment  | 

1 Answer 1

Reset to default 0

First off, adjust your query so you're only returning top level posts (the parent posts in this instance)

add_filter('pre_get_posts', 'only_top_level_posts');

function only_top_level_posts($query) {
    // wrap some conditional statements around here so it doesn't affect every query, just limit to whatever queries you need it in
    $query->set( 'post_parent', 0 );
    return $query;
}

This will return only the top level posts.

Then, inside the loop, you can use either get_posts() to get the children of said post (returning the most recently posted):

$args = [
    'post_parent' => $post->ID,
    'posts_per_page' => 1,
    'orderby' => 'post_date',
    'order' => 'DESC'
];

$children = get_posts($args);

or use get_children(), which works in a similar way to get_posts() with similar arguments. Once you have your child post, you can output whatever you need to from it.

Either one of those approaches will return an array which you can then pick apart to get the information you need.

Hopefully that gives you something to start playing around with, I'm sure there's more than one way to do what you're after but that's how I'd start to approach it.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745177316a288983.html

最新回复(0)