首页 > 解决方案 > 无法获取 WP_Query 自定义帖子类型的类别帖子

问题描述

我对自定义帖子类型的 WP_Query 有一些问题,我无法按类别获取自定义帖子。我有:

function my_blocks_render_function( $attributes ) {

$args = array(
    'post_type' => 'my_cpt',
    'posts_per_page' => $attributes['numberOfPosts']
);
if($attributes['postCategories']) {
    $args['cat'] = $attributes['postCategories'];
}
$query = new WP_Query($args);
$posts = '';
if($query->have_posts()) {
    $posts .= '<ul>';
    while ($query->have_posts()) {
        $query->the_post();
        $posts .= '<li><a href="' . esc_url( get_the_permalink() ) . '">' . get_the_title() . '</a></li>';
    }
    $posts .= '</ul>';
    wp_reset_postdata();
    return $posts;
} else {
    return '<div>' . __("No Posts Found", "my-blocks") . '</div>';
}}

使用'post_type'=>'post',一切正常,但自定义帖子类型没有。如果未选择 postTypes,我将获得所有自定义帖子,但如果是“未找到帖子”。

我究竟做错了什么?我尝试添加 tax_query,但结果相同。我 var_dump 我的 postCategories 并获得正确的 ID。

对不起我的英语,谢谢。

标签: wordpress

解决方案


这将正常工作。

$taxonomy='our_project_category';
$tax_terms = get_terms($taxonomy, array('hide_empty' => false));
foreach($tax_terms as $term_single) {      
$categories_id= 2; //category_id  

 $args_new  =  array(
  'post_type' => 'our-project',
  'posts_per_page' => 6,
  'tax_query' => array(
    array(
      'taxonomy' => 'our_project_category',
      'field'    => 'term_id',
      'terms'    => $categories_id,
    ),
  ),
);
$loop_new = new WP_Query($args_new);

if($loop_new->have_posts()) {
while($loop_new->have_posts()) : $loop_new->the_post();

//content

endwhile; wp_reset_query();
    endif;
    ?>

推荐阅读