簡體   English   中英

Wordpress-每頁的帖子不適用於特定的類別-slug.php

[英]Wordpress - Posts per page not working for specific category-slug.php

我有一個特定的category-slug.php頁面。

我想顯示第一個類別“ banner-ads”,每頁僅發布1個帖子,然后在其下方顯示“特征”類別中的每頁3個帖子。

我不想使用: ** query_posts('posts_per_page = 4'); **

我已經嘗試過pre_get_posts函數,但似乎無法正常工作。

現在,每頁顯示的帖子數是我在“設置”->“閱讀”中分配的數量

這是我當前的代碼:

$args1 = array(
    'category_name' => 'banner-ads',
    'posts_per_page' => 1
    );


$the_query = new WP_Query( $args1 );


while ( $the_query->have_posts() ) :
    $the_query->the_post();
    ar2_render_posts( null, array ( 'type' => 'node' ), true );
endwhile;

wp_reset_postdata();


$args2 = array(
    'category_name' => 'featured',
    'posts_per_page' => 3
    );

$query2 = new WP_Query( $args2 );

while( $query2->have_posts() ):
    $query2->next_post();
    ar2_render_posts( null, array ( 'type' => 'traditional' ), true );
endwhile;

wp_reset_postdata();

您尚未重置: wp_reset_postdata();

有關類別的有用信息: http : //codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters

這是我的第一個循環頁面之一:

<?php 
$postq1 = new WP_Query(
 array(
  'post_type' => array('post','yourcustom'),
  'posts_per_page' => 1, 
  'category_name'=>'banner-ads')
 );
if($postq1->have_posts()):
    while ( $postq1->have_posts() ) :
        $postq1->the_post();?>
<article id="post-<?php the_ID();?>">....</article>
<?php 
    endwhile;
endif;
wp_reset_postdata();
?>

第二循環:

<?php 
$postq2 = new WP_Query(
 array(
  'post_type' => array('post','yourcustom'),
  'posts_per_page' => 3,
  'category_name'=>'featured')
);
if($postq2->have_posts()):
    while ( $postq2->have_posts() ) :
        $postq2->the_post();?>
<article id="post-<?php the_ID();?>">....</article>
<?php 
    endwhile;
endif;
wp_reset_postdata();
?>

...使用query_posts()剩下的代碼;

好吧,我終於明白了。 如果要強制其占用一定數量的帖子,請添加具有其功能的過濾器,然后在循環結束時將其刪除。 我在第二個循環中意識到ar2_render_posts()函數與代碼沖突,因此我選擇從頭開始重做該函數,因為它基本上是布局函數。

add_filter('post_limits', 'my_post_limits');

function my_post_limits( $limit ) {
    if ( in_category('banner-ads') ) {
        return 'LIMIT 0, 3';
    }
    return $limit;
}

    $args1 = array(
        'category_name' => 'banner-ads'
        );


    $the_query = new WP_Query( $args1 );


    while ( $the_query->have_posts() ) :
        $the_query->the_post();
        ar2_render_posts( null, array ( 'type' => 'node' ), true );
    endwhile;

    wp_reset_postdata();
    remove_filter('post_limits', 'my_post_limits');

這非常簡單,只需在ar2_render_posts alter query_args ar2_render_posts

ar2_render_posts( null, array ( 
     'query_args' => array ( 'posts_per_page' => 1 ),
), true );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM