繁体   English   中英

如何将自定义帖子类型查询的帖子数限制为3?

[英]How do I limit the Number of Posts to 3 for a Custom Post Type Query?

我试图在我的主WordPress页面上显示自定义帖子类型的结果。

到目前为止这是我的代码:

                <?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,添加到args数组中。 它根本不显示任何结果。 我做错了什么,或者有另一种方法来实现同样的结果?

如果它是相关的,我使用的插件是高级自定义字段和自定义帖子类型。

提前致谢!

解决了:

我实际上已经弄明白了,并且认为我会分享我是如何解决它的。

'posts_per_page'=> 3正在运行,但它只显示该类型的最后3个帖子未被if(isset($ my_custom_fields ['availability'])&& $ my_custom_fields ['availability'] =='过滤“):

为了限制由此字段过滤的帖子,我添加了自己的计数器,并将其设置为最大值为3.我将上面的行更改为if(isset($ my_custom_fields ['availability'])&& $ my_custom_fields [ 'availability'] =='Sold'&&($ postcount <3)):并添加$ postcount ++; 在循环内。

再次感谢你的帮助。 我希望这可以帮助其他任何人。

您找到的解决方案只能在某些条件下工作。 如果没有三个帖子的可用性设置为“可用”,那么您检索的集合(可能是前十个),您就没有足够的资源。 您可以执行自定义查询,指定自定义字段名称和值,如WP_Query文档中所述

$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' );
}

这个答案的来源

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM