【问题标题】:Query custom posts type by custom field on archive page通过存档页面上的自定义字段查询自定义帖子类型
【发布时间】:2017-01-05 12:50:33
【问题描述】:

我在 archive-mypostype.php 模板中使用以下查询来列出具有特定自定义字段值的自定义帖子。

$args = array(
   'numberposts'    => -1,
   'post_type'      => 'mypostype',
   'meta_key'       => 'custom_field_name',
   'meta_value'     => true,
   'paged'          => get_query_var( 'paged' ),
);

$wp_query = new WP_Query( $args );

if ( $wp_query->have_posts() ) : 
while ( $wp_query->have_posts() ) : $wp_query->the_post();

这些帖子被分配到自定义分类。该查询适用于自定义帖子类型的根存档,但查看每个分类存档页面会显示所有帖子,而不仅仅是当前分类的帖子。如何修改查询,以便仅查看当前分类档案的帖子?

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    您可以查看WP_Query codex 页面及其taxonomy 参数here

    使用此参数,您将能够检索特定分类中的帖子。

    $args = array(
       'numberposts'    => -1,
          'post_type'      => 'mypostype',         
          'paged'          => get_query_var( 'paged' ),
          'meta_query'     => array(
               array(
                   'key'=> 'custom_field_name',
                   'value'=> 'true',
               )
          ),
          'tax_query' => array(
               array(
                   'taxonomy' => 'your-taxonomy', // change this with the cpt taxonomy name
                   'field'    => 'slug',
                   'terms'    => get_query_var( 'category_name' ), // change it with the query var needed
               ),
           )
    );
    

    希望对你有帮助。

    【讨论】:

    • 谢谢,但这不是我想要的,抱歉,如果我不清楚的话。我只想能够动态显示每个分类的帖子,由上面的自定义字段过滤。如果我删除 $wp_query,它会在访问每个分类存档页面时工作,但添加此查询会显示每个分类存档页面的所有帖子
    猜你喜欢
    • 1970-01-01
    • 2017-11-21
    • 1970-01-01
    • 1970-01-01
    • 2016-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-10
    相关资源
    最近更新 更多