簡體   English   中英

get_query_var('cat')是否也獲取子類別帖子?

[英]Does get_query_var('cat') fetches child Category Posts as well?

在category.php中,我使用自定義查詢來獲取帖子:

                <?php

                    $cat_id = get_query_var('cat'); 
                    $args = array(
                        'posts_per_page' => 2,
                        'orderby' => 'date',
                        'cat' => $cat_id
                    );

                    query_posts($args);
                    // the Loop
                    get_template_part('aa_HomeLoopMain');

                ?>

我正在使用get_query_var('cat')來獲取當前類別的類別帖子,我認為這只會給出帶有$cat_id的類別ID的類別帖子,而不是其子類別的帖子

你做錯了。 永遠不要使用query_posts ,它會破壞主查詢對象,重新運行查詢,而且速度很慢,所有這些都會對性能和SEO以及依賴於主查詢的其他功能產生負面影響。 另外,如果這是您的主要查詢,則根本不應該使用自定義查詢,而應使用pre_get_posts在執行之前修改主要查詢。

get_query_var( cat )僅返回查詢的類別,而不返回其子類別。

您應該刪除query_posts部分並將以下內容添加到您的functions.php

add_action( 'pre_get_posts', function ( $q )
{
    if (    !is_admin()
         && $q->is_main_query()
         && $q->is_category()
    ) {
        $q->set( 'posts_per_page', 6 );
    }
});

編輯

您應該總共查詢6個帖子,我已經更新了。 您可以嘗試以下循環

if ( have_posts() ) {
    while( have_posts() ) {
        the_post();

        if ( 1 <= $wp_query->current_post ) {
            // Add your markup for column one, this will display 2 posts
        } else {
            // Add your markup for column two, this will display 4 posts
        }
    }
}

編輯2

由於某些原因,我無法從手機發布評論,但我認為您使用的代碼有誤。 我已經更新了代碼以顯示循環。 確實有效。 如果沒有,則其他內容會破壞您的頁面,例如query_posts

暫無
暫無

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

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