我正在尝试从名为菜单项的自定义帖子类型输出,但由于某种原因它无法正常工作,有人可以解释我将如何更改以下查询以允许类别correclty我只是得到空结果
<?php
/*
* Loop through Categories and Display Posts within
*/
$post_type = 'menu_items';
// Get all the taxonomies for this post type
$taxonomies = get_object_taxonomies( array( 'post_type' => $post_type ) );
foreach( $taxonomies as $taxonomy ) :
// Gets every "category" (term) in this taxonomy to get the respective posts
$terms = get_terms( $taxonomy );
foreach( $terms as $term ) : ?>
<?php
$args = array(
'post_type' => $post_type,
'posts_per_page' => -1, //show all posts
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => array ( 'salads-raw-things' ),
),
array(
'taxonomy' => $taxonomy,
'field' => 'slug',
'terms' => $term->slug,
)
)
);
$posts = new WP_Query($args);
if( $posts->have_posts() ): while( $posts->have_posts() ) : $posts->the_post(); ?>
<ul class="menu-list">
<li class="menu-item"><?php echo get_the_title(); ?></p>
<p class="number">
<?php the_field('dish_number',$posts->ID); ?>
</li>
<?php endwhile; endif; ?>
<?php endforeach;
endforeach; ?>
答案 0 :(得分:0)
您只需要循环以创建tax_query参数。每次循环运行时都会覆盖您的查询。
你必须这样做:
foreach( $taxonomies as $taxonomy ) :
// Gets every "category" (term) in this taxonomy to get the respective posts
$terms = get_terms( $taxonomy );
foreach( $terms as $term ) : ?>
<?php
tax_query[] = array(
'taxonomy' => $taxonomy,
'field' => 'slug',
'terms' =>$term
);
endforeach ;
endforeach ;
然后,您只需为一个$args
WP_Query
$args = array(
'post_type' => $post_type,
'posts_per_page' => -1, //show all posts
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => array ( 'salads-raw-things' ),
),
$tax_query
)
);
$query = new WP_Query($args);
不要忘记在每个分类法之间正确设置所需的关系。
希望它能给你一些提示让它有效!