如何限制自定义帖子类型查询的帖子数量为3?
我想在我的主wordpress页面上显示自定义帖子类型的结果。如何限制自定义帖子类型查询的帖子数量为3?
这是我到目前为止的代码:
<?php
wp_reset_query();
$args=array(
'post_type' => 'rooms',
'post_status' => 'publish',
'caller_get_posts'=> 1
);
$my_query = null;
$my_query = new WP_Query($args);
if($my_query->have_posts()) { ?>
<TABLE border="1" cellspacing="50">
<TR>FEATURED ACTIVE LISTINGS</tr>
<?php
while ($my_query->have_posts()) : $my_query->the_post();
$my_custom_fields = get_fields(get_the_ID());
if(isset($my_custom_fields['availability']) && $my_custom_fields['availability'] == 'Available'):
?>
<tr><td><?php echo the_post_thumbnail('thumbnail');?>
<br>UNIT <?php echo the_field('unit_number'); ?> <?php echo the_field('bedrooms'); ?>BEDS/<?php echo the_field('bathrooms'); ?>BA
<br>$<?php echo the_field('price'); ?></td>
</tr>
<?php
endif;
endwhile; ?>
</TABLE>
<?php }
wp_reset_query();
?>
这工作。但是,如果我尝试将'posts_per_page' => 3,
添加到参数数组中。它根本不显示任何结果。我做错了什么,或者是否有其他方法来达到同样的结果?
如果相关,我使用的插件是高级自定义字段和自定义帖子类型。
在此先感谢!
解决:
其实我已经想通了我自己,以为我会分享我如何解决它。
“posts_per_page” => 3工作,但它只会显示该类型的最后3帖这是不被如果(isset($ my_custom_fields [“可用性”])& & $ my_custom_fields过滤[“可用性” ] =='Available'):
为了限制被此字段过滤的帖子,我添加了自己的计数器并将其设置为最大值3.我将上面的行更改为if(isset( $ my_custom_fields ['availability'])& & $ my_custom_fields ['availability'] =='已售出'& &($ postcount < 3)):and added $ postcount ++;在循环内。
再次感谢您的帮助。我希望这有助于其他任何人。
您发现的解决方案只能在某些条件下工作。如果没有三个帖子的可用性设置为“可用”(可能是前十个),那么您将没有足够的可用性。你可以做一个自定义的查询,而不是指定的自定义字段名称和值,如WP_Query documentation描述:
$args=array(
'post_type' => 'rooms',
'post_status' => 'publish',
'meta_key' => 'availability',
'meta_value' => 'Available',
'posts_per_page' => 3,
'ignore_sticky_posts'=> 1
);
$my_query = new WP_Query($args);
在functions.php中,你应该宁可做到以下几点:
// posts per page based on content type
function themename_custom_posts_per_page($query)
{
switch ($query->query_vars['post_type'])
{
case 'content_type_name': // Post Type named 'content_type_name'
$query->query_vars['posts_per_page'] = 3; //display all is -1
break;
}
return $query;
}
if(!is_admin())
{
add_filter('pre_get_posts', 'themename_custom_posts_per_page');
}
这Source回答
这个解决方案对我来说很好 – 2017-11-06 01:02:15
您使用的是什么版本的WordPress? – Furgas 2012-02-23 19:03:22
Wordpress 3.3.1 – wiseman7687 2012-02-23 19:08:38
'caller_get_posts' [已被弃用](http://codex.wordpress.org/Class_Reference/WP_Query#Sticky_Post_Parameters)。改为使用'ignore_sticky_posts'。 – 2012-02-23 19:08:53