簡體   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