最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - WP_Query - How To Query Only Custom Posts With No Children of Their Own?

programmeradmin4浏览0评论

I have an (apparently) unique problem I've been unable to find an answer to anywhere, or my head has simply become stewed.

Using WP_Query to only show child posts is easy enough, or to display only the latest post. However, I need to show the latest post of a custom post type given the following conditions:

  1. If a post has children, do not include the parent in the query, only include the children
  2. If a post has no children, include it in the query
  3. If these posts contain meta_key_value A or B or C, include them in the query (this works)
  4. Display the latest post that fits these criteria

Basically, I need to only query posts that do not have children of their own (as child posts and posts with no children fit this). In this project, children posts are parts of the parent, so users need to be directed to the latest part (the child, not the parent). However, some posts have no parts, therefore they must be included in the query also.

I was able to work out this logic when creating a single custom post template by using a custom meta key and checking if $post->post_parent == 0 or $post->post_parent != 0, so I could display the correct variable based on the current post, but checking for this easily in WP_Query all at once has me confused. Granted, in my template, I had to manually set boolean variables and use those in if statements since determining all the three conditions wasn't working (I'm no php expert). Since multi_has_yes meta key must be set on parents and their children so the template loads in all the data correctly, I can't simply include posts that have this key, and single posts with no children have multi_has_no.

Template code that works (not the WP_Query):

if ( $has_multi == 'multi_has_yes' && $post->post_parent == 0) {
    // It's a parent
    $has_a_parent = false;
    $has_one_multi = false;
    $post_parent_status = 'parent_post';
} else if ($has_multi == 'multi_has_no' && $post->post_parent == 0){
    // It's a single post, not a parent or child post
    $has_a_parent = false;
    $has_one_multi = true;
    $post_parent_status = 'single_post';
} else if ( $has_multi == 'multi_has_yes' && $post->post_parent != 0) {
    // It's a single part, not a single post or parent
    $has_a_parent = true;
    $has_one_multi = false;
    $post_parent_status = 'single_part';
    $parent_id = $post->post_parent;
    $parent_link = get_the_permalink($parent_id);
    $parent_title = get_the_title($parent_id);
}
发布评论

评论列表(0)

  1. 暂无评论