【问题标题】:Querying and displaying posts in taxonomy, custom post type分类查询和显示帖子,自定义帖子类型
【发布时间】:2019-09-24 09:20:02
【问题描述】:

我有一个名为 resources 的自定义帖子类型:

register_post_type(
    'resources',
    tp_build_post_args(
        'resources', 'Resource', 'Resources',
        array(
            'menu_icon'     => 'dashicons-welcome-write-blog',
            'menu_position' => 20,
            'public'      => true,
            'supports' => array('editor', 'title','author','thumbnail', 'revisions'),
            'taxonomies' => array('sector', 'subject', 'type'),
        )
    )
);

还有一个名为type的分类法:

register_taxonomy(  
    'type', 
    'type', 
    array(  
        'hierarchical' => true,  
        'label' => 'Type',  
        'query_var' => true,
        'rewrite' => array(
            'slug' => 'type', 
            'with_front' => false 
        ) 
    )
);

类型可以是以下之一:

  • 博客
  • 新闻
  • 网络研讨会

我正在尝试使用wp_query 显示resources 下的所有帖子以及type“新闻”。但是,它会返回所有帖子。

我的方法在哪里分崩离析:

$card_count = 4;
$resource_type = 'News';

$args = array(  
    'post_type' => 'resources',
    'post_status' => 'publish',
    'posts_per_page' => $card_count,
    //'cat' => $resource_type,
    'tax_query' => array(
        array(
            'taxonomy' => 'type',
            'terms' => $resource_type,
        )
    )
);

【问题讨论】:

    标签: php wordpress custom-post-type


    【解决方案1】:

    试试看:

    'tax_query' => array( array( 'taxonomy' => 'type', 'terms' => $resource_type, 'field' => 'name', // or 'slug' 'operator' => 'IN' ) ),

    【讨论】:

      【解决方案2】:

      我的猜测是您需要指定您要查找的是分类的name,默认情况下它可能正在查找ID

      $args = array(  
      'post_type' => 'resources',
      'post_status' => 'publish',
      'posts_per_page' => $card_count,
      //'cat' => $resource_type,
      array(
              'taxonomy'         => 'type',
              'terms'            => $resource_type,
              'field'            => 'name',
              'operator'         => 'IN',
              'include_children' => true,
          )
      );
      

      您可以阅读文档以获得更好的理解 - 或者,如果您想作弊,这是一个不错的生成器:https://generatewp.com/wp_tax_query/

      【讨论】:

        猜你喜欢
        • 2022-07-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-28
        • 1970-01-01
        • 2016-02-19
        相关资源
        最近更新 更多