我正在寻找以下代码来对我的自定义帖子类型(产品类型)进行排序。这样我的活动页面将只显示带有术语“ Oil”的帖子,而不是“ Fuel”和“ Tires”。
$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();
}
//编辑,作为对以下三个答案的答复
我假设foreach循环是WP_Query方法的替代,但是tax_query对我来说是新的,现在我知道它存在,所以我在抄本中查找了它,但是仍然无法正常工作。我坚信这就像我在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'
),
),
);
试试下面的代码:
<?php
$myposts = get_posts(array(
'showposts' => -1,
'post_type' => 'Products',
'tax_query' => array(
array(
'taxonomy' => 'products_cat',
'field' => 'slug',
'terms' => 'oil'
);
)
)
);
foreach ($myposts as $mypost) {
echo $mypost->post_title . '<br/>';
echo $mypost->post_content . '<br/>';
echo get_the_post_thumbnail( $mypost->ID );
}
?>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句