【问题标题】:How to check if wp_query results found any custom post_type?如何检查 wp_query 结果是否找到任何自定义 post_type?
【发布时间】:2021-09-20 19:56:52
【问题描述】:

在我的 WordPress v5.8.1 中,我在 taxonomy.php 中有以下查询以获取帖子列表。

$args = array(
 'post_type' => array('song', 'dance'),
 'post_status' => 'publish',
 'posts_per_page' => 10,
 );
 query_posts($args);

查询返回来自post_type 的帖子。

我想在同一页面中创建一个菜单,我想在其中检查查询结果是否找到了来自特定 post_type 的帖子。菜单看起来像这样。

  • 此分类有来自 Song、Dance 的帖子(如果找到来自两个 post_type 的帖子)或

  • 此分类有来自 Song 的帖子(如果找到来自 Song post_type 的帖子)

在循环中尝试了以下内容:

    $song_count = wp_posts_count('song')->found_posts;
    $dance_count = wp_posts_count('dance')->found_posts;
     if ($song_count=>0 {
     /** code goes here **/
    }

Above 返回整个 WordPress 的计数,而不仅仅是当前分类法。

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    您可以将结果存储在变量中,但我是否正确理解了这个问题?

    $args = array(
        'post_type' => array('song', 'dance'),
    
        // or 'post_type' => get_post_type($post->ID),
        // conditions are no longer necessary
    
        'post_status' => 'publish',
        'posts_per_page' => 10,
    );
    $results = query_posts($args);
    
    if($results) {
        $count = 0;
        $current_post_type = get_post_type($post->ID);
        $current_post_type_name = get_post_type_object(get_post_type())->labels->singular_name); // ajust with 2 variables for multiple results
        foreach($results as $result) {
            // if request is in a single custom post  
            if($result->post_type == $current_post_type) {
                $count++;
            }       
        }
        if($count > 0) {
            echo $count . $current_post_type_name;
        }
    }
    else {
        // no results
    }
    

    【讨论】:

    • 我已经更新了我的问题。我想在同一页面中创建一个菜单,我想在其中检查查询结果是否找到了来自特定 post_type 的帖子。菜单看起来像这样。
    • 您可以将 post_type 值更改为:'post_type' => get_post_type($post->ID)
    猜你喜欢
    • 1970-01-01
    • 2010-10-26
    • 2017-12-16
    • 2011-10-31
    • 2018-06-18
    • 2021-11-10
    • 2018-10-08
    • 2021-09-08
    • 2018-09-14
    相关资源
    最近更新 更多