如何从特定类别查询自定义帖子tye

时间:2017-11-30 15:38:24

标签: wordpress custom-post-type custom-wordpress-pages

我需要显示来自自定义帖子类型的帖子,但是从一个特定类别,我使用下面的代码,但显示所有类别的所有帖子,而不仅仅是7。

<?php
    $args = array( 'post_type' => 'tour', 'posts_per_page' => 10, 'cat=7' , 'taxonomy' => 'tourcat');
    $loop = new WP_Query( $args );
    while ( $loop->have_posts() ) : $loop->the_post();
        echo "TEST TEST TEST TEST";
        echo the_title();
        echo '<div class="entry-content">';
        the_content();
        echo '</div>';
    endwhile;
?>

4 个答案:

答案 0 :(得分:0)

这不是WP Query的有效参数。

cat=7

请在此阅读有关分类学查询的信息,他们应该按照您的要求进行操作: https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters

答案 1 :(得分:0)

目前,您的$args数组只保存一个cat=7元素,这是将参数传递给WP_Query构造函数的错误方法。请注意,如果使用空格格式化$args数组,问题会更加明显:

$args = array(
    'post_type' => 'tour',
    'posts_per_page' => 10,
    'cat=7' , /* Here is the problem */
    'taxonomy' => 'tourcat'
);

我相信您的$args数组应如下所示:

$args = array(
    'post_type' => 'tour',
    'posts_per_page' => 10,
    'cat' => 7,
    'taxonomy' => 'tourcat'
);

答案 2 :(得分:0)

此,

$args = array( 'post_type' => 'tour', 'posts_per_page' => 10, 'cat=7' , 'taxonomy' => 'tourcat');

应该是,

 $args = array( 'post_type' => 'tour', 'posts_per_page' => 10, 'tax_query' => array( array( 'taxonomy' => 'tourcat','field' => 'ID','terms' => '7' ) ));

答案 3 :(得分:0)

试试这个:

$postData = new WP_Query(array(
    'post_type' => 'tour',   // custom post type
    'posts_per_page'=>10,
    'tax_query' => array(
        array(
            'taxonomy' => 'tourcat', //custom taxonomy name
            'field' => 'id',
            'terms' => 7
        )
    )
));
if($postData->have_posts()):
    while ($postData->have_posts()): $postData->the_post();
        echo "TEST TEST TEST TEST";
        the_title();
        echo '<div class="entry-content">';
        the_content();
        echo '</div>';  
    endwhile;
endif;
相关问题