Leanest way to get all top parent posts that have at least one child
-
I am creating a Dashboard widget to display a tree view of hierarchical posts.
In order to not hit performance issues on sites with hundreds, potentially thousands of posts, I want to add a “pagination”, so the widget would initially display say 50 Top Parent Posts maximally (but all their children.)
Thus, I need a query that allows me to get Top Parent Posts.
That is easy, I just run aget_posts()
with'post_parent' => 0,
, or aget_pages()
with'parent' => 0,
However, this will return also Top Parent Posts that have no children
That is no problem if I have no pagination, as I can simply exclude those posts from my list usingget_children()
to remove the posts without children from the results.But, when I paginate, this produces a problem, because the initial query will find all Top Parent Posts, which might include those without children. If I paginate say by 10 posts, and the first 10 posts found have all no children, my list at the end will be empty, because I remove all posts without children and thus, of the 10 results, none is returned.
I would need to query the posts that are Top Level Parents and have children, in the same query run in order to avoid this issue.
But there is no “has_children” or similar argument in WP_Query (or get_posts) as far I know.The other option would be to run the query twice, but then I knock out the whole purpose of pagination since I would have to get all posts in the first run, and then filter those in a second run.
My third and current option is to simply “explain” to the user that they might see “no results” just because the (example) first 10 results have no children, thus paginating (offset + page number) will eventually return results. However this is cumbersome and bad UX.
What would be the least performance intensive way to get all Top Level Posts, that have at least one child?
- This topic was modified 3 years, 5 months ago by .
- The topic ‘Leanest way to get all top parent posts that have at least one child’ is closed to new replies.