【发布时间】:2015-01-07 16:52:12
【问题描述】:
我想让下面的代码对我的自定义 posttype(产品类型)进行排序。 这样我的活动页面将只显示带有“石油”一词的帖子,而不是“燃料”和“轮胎”。
$args = array(
'post_type' => 'Products',
'posts_per_page' => -1
);
$my_query = new WP_Query( $args );
if ($my_query->have_posts()) {
while($my_query->have_posts() ) {
echo '<div class="custom-post">';
$my_query->the_post();
echo '<p>' . the_content() . '</p>';
the_post_thumbnail();
echo '</div>';
}
wp_reset_postdata();
}
// 编辑,作为对以下 3 个答案的回复
我假设 foreach 循环是 WP_Query 方法的替代品,但 tax_query 对我来说是新的,现在我知道它存在,我在 codex 中查找它,但它仍然无法工作。老实说,我认为这就像我在 tax_query 中错误地命名一样简单,所以我将在这里展示我的分类代码:
function my_custom_taxonomies() {
register_taxonomy(
'product-type',
'products',
array(
'label' => 'Type of Product',
'rewrite' => array( 'slug' => 'race-products' ),
'hierarchical' => true,
)
);
}
add_action( 'init', 'my_custom_taxonomies' );
以及对 $args 的更改:
$args = array(
'post_type' => 'Products',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'product-type',
'field' => 'slug',
'terms' => 'oil'
),
),
);
【问题讨论】: