3

我正在尝试在我的主 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 正在工作,但它只会显示没有被 if(isset($my_custom_fields['availability']) && $my_custom_fields['availability'] == 'Available 过滤的该类型的最后 3 个帖子'):

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

再次感谢您的帮助。我希望这对其他人有帮助。

4

2 回答 2

5

您找到的解决方案仅在某些条件下有效。如果在您检索的集合中没有三个将可用性设置为“可用”的帖子(可能是前十个),那么您将没有足够的信息。您可以执行自定义查询,而不是指定自定义字段名称和值,如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);
于 2012-02-24T22:15:54.847 回答
4

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

这个答案的来源

于 2012-11-01T14:59:58.057 回答