$posts = query_posts(array('post_type'=>'sedan', 'category'=>'1', 'posts_per_page'=>'4'));
上面查询中的category
参数似乎没有像预期的那样工作。它显示了Sedan
帖子类型的所有帖子,但我只想在Sedan post type
中指定category ID = 1
的类别。
Try with
$posts = query_posts(array('post_type'=>'sedan', 'cat'=>'1', 'posts_per_page'=>'4'));
cat
代替category
。
还有不要在查询中使用 query_posts()
。
使用get_posts()
或WP_Query()
你也可以这样做:
$posts = get_posts(array('post_type'=>'sedan', 'category'=>'1', 'posts_per_page'=>'4'));
比修改主查询更安全。
我自己一直比较喜欢WP_Query
。
$args = array(
'post_type'=>'sedan',
'cat'=>'1',
'posts_per_page'=>'4'
);
$posts = new WP_Query($args);
$out = '';
if ($posts->have_posts()){
while ($posts->have_posts()){
$posts->the_post();
$out .= 'stuff goes here';
}
}
wp_reset_postdata();
return $out;
尝试使用get_posts
引用
$args = array( 'posts_per_page' => 5, 'offset'=> 1, 'category' => 1 );
$myposts = get_posts( $args );
或者另一个选项是使用WP_Query
$new = new WP_Query('post_type=discography&category_name=my-category');
while ($new->have_posts()) : $new->the_post();
the_content();
endwhile;
或cat id
$cat_id = get_cat_ID('My Category');
$args=array(
'cat' => $cat_id,
'post_type' => 'discography',
'post_status' => 'publish',
'posts_per_page' => 5,
'caller_get_posts'=> 1
);
$new = new WP_Query($args);
我就是这么做的。
$args=array(
'posts_per_page' => 50,
'post_type' => 'my_custom_type'
'tax_query' => array(
array(
'taxonomy' => 'category', //double check your taxonomy name in you db
'field' => 'id',
'terms' => $cat_id,
),
),
);
$wp_query = new WP_Query( $args );