首頁  >  文章  >  後端開發  >  掌握 WP_Query:利用循環的力量

掌握 WP_Query:利用循環的力量

PHPz
PHPz原創
2023-09-01 10:49:091192瀏覽

标题重写为:Mastering WP_Query: Harnessing the Power of the Loop

正如我在本系列簡介中概述的那樣,WP_Query 類別有四個主要元素:

  • 查詢的參數,使用本系列將詳細介紹的參數
  • 查詢本身
  • 循環,它將輸出帖子內容、標題或您想要顯示的任何內容
  • 結束:關閉 if 和 while 標籤並重置發布資料

在本教程中,我將向您展示如何透過 WP_Query 使用循環,包括建立循環的兩種主要方法以及如何使用多個循環。

循環適合的位置

#如果沒有循環,頁面上將不會顯示任何內容。 WordPress 使用您定義的參數執行查詢後,需要告知它從取得的資料輸出什麼。這就是循環出現的地方。

因此循環出現在查詢之後,它使用三個標籤:

  • if( $query->have_posts() ) 檢查是否有任何貼文。它透過檢查查詢的 post_count 屬性的值是否小於 current_post 1 的值來實現這一點。
  • while( $query->have_posts() ) 只要有要檢索的帖子, 就會對每個帖子重複循環。正如你所看到的,這個 have_posts() 方法與我們之前呼叫的檢查是否有貼文的方法相同。請記住,此方法不會增加帖子計數器。它只是讓我們知道循環中是否有任何帖子或我們是否處於循環末尾。一旦到達結尾,它也會自動倒回循環。
  • $query->the_post() 存取該特定貼文。它還執行其他一些操作,例如檢索下一篇文章,並增加帖子計數器。它還設定了全球發布數據供我們使用。

當您在循環內時,不應呼叫 have_posts() 方法。這是因為 have_posts() 會將迴圈倒回開頭,您將陷入無限迴圈。

現在,這是循環在 WP_Query 類別中的位置:

<?php

$args = array(
    // Arguments for your query.
);

// Custom query.
$query = new WP_Query( $args );

// Check that we have query results.
if ( $query->have_posts() ) {

    // Start looping over the query results.
    while ( $query->have_posts() ) {
        $query->the_post();
        // Contents of the queried post results go here.
    }

}

// Restore original post data.
wp_reset_postdata();

?>

運行循環後,剩下要做的就是使用 wp_reset_postdata() 進行整理。

循環結構

循環的結構方式取決於您想要從帖子中顯示的資料。下面是一個範例循環,它輸出貼文標題、特色圖像和摘錄。您可以在存檔頁面上使用這樣的循環。

<?php

$args = array(
    // Arguments for your query.
);

// Custom query.
$query = new WP_Query( $args );

// Check that we have query results.
if ( $query->have_posts() ) {

    // Start looping over the query results.
    while ( $query->have_posts() ) {

        $query->the_post();

        ?>

        <article id="post-<?php the_ID(); ?>" <?php post_class( 'left' ); ?>>
            <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
                <?php post_thumbnail( 'thumbnail' );?>
            </a>
            <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
                <?php the_title(); ?>
            </a>
            <?php the_excerpt(); ?>
        </article>

        <?php

    }

}

// Restore original post data.
wp_reset_postdata();

?>

此循環準確地顯示了我上面所描述的內容:特色圖像、標題和摘錄。

進一步循環:檢查內容

但有時您可能想在帖子列表之前添加標題,或者您可能想將它們全部包含在包含元素中。如果您只是在循環之前添加此內容,則無論查詢是否實際返回任何數據,它都會輸出,這意味著您可能有一個標題下面沒有任何內容,或者有一些不必要的標記。

透過將封閉元素或標題放入 if 標記中,可以輕鬆解決這個問題:

<?php

$args = array(
    // Arguments for your query.
);

// Custom query.
$query = new WP_Query( $args );

// Check that we have query results.
if ( $query->have_posts() ) {

    
    echo '<section class="clear">';
        echo '<h2>' . __( 'Heading', 'tutsplus' ) . '</h2>';
    
        // Start looping over the query results.
        while ( $query->have_posts() ) {
    
            $query->the_post();
    
            ?>
    
            <article id="post-<?php the_ID(); ?>" <?php post_class( 'left' ); ?>>
                <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
                    <?php post_thumbnail( 'thumbnail' );?>
                </a>
                <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
                    <?php the_title(); ?>
                </a>
                <?php the_excerpt(); ?>
            </article>
    
            <?php
    
        }
    
    echo '</section>';

}

// Restore original post data.
wp_reset_postdata();

?>

在這裡您可以看到我已經檢查了我的查詢是否檢索到了任何帖子,如果有,我已經打開了一個包含元素並添加了一個標題。

如果您想將查詢結果輸出為列表,這也很有用。假設我想建立給定類別中所有帖子的清單。 ul 元素不在我的循環內,因為它與某一特定帖子無關,但我只想在有帖子時輸出它。所以我用這個:

<?php

$args = array(
    'category_name' => 'category-slug',
    'post_type' => 'post'
);

// Custom query.
$query = new WP_Query( $args );

// Check that we have query results.
if ( $query->have_posts() ) {

    echo '<ul class="category posts">';

        // Start looping over the query results.
        while ( $query->have_posts() ) {

            $query->the_post();

            ?>

            <li <?php post_class( 'left' ); ?>>
                <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
                    <?php the_title(); ?>
                </a>
            </li>

            <?php
    
        }

    echo '</ul>';

}

// Restore original post data.
wp_reset_postdata();

?>

這會檢查查詢是否已取得任何帖子,如果是,則開啟 ul 元素,然後執行循環。

運行額外循環

要注意的是,雖然您可以使用 WP_Query 運行多個循環,但您必須重置發布資料並啟動 WP_Query 的第二個實例才能運行做這個。這是因為每個循環都將根據不同的參數輸出資料。

此範例顯示第一篇文章的摘錄和特色圖像,然後僅顯示每個後續文章的標題:

<?php

// First query arguments.
$args1 = array(
    'post_type' => 'post',
    'posts_per_page' => '1'
);

// First custom query.
$query1 = new WP_Query( $args1 );

// Check that we have query results.
if ( $query1->have_posts() ) {

    // Start looping over the query results.
    while ( $query1->have_posts() ) {

        $query1->the_post();

        ?>

        <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
            <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
                <?php post_thumbnail( 'thumbnail' );?>
            </a>
            <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
                <?php the_title(); ?>
            </a>
            <?php the_excerpt(); ?>
        </article>

        <?php

    }

}

// Restore original post data.
wp_reset_postdata();

// Second query arguments.
$args2 = array(
    'offset' => '1',
    'post_type' => 'post'
);

// Second custom query.
$query2 = new WP_Query( $args2 );

// Check that we have query results.
if ( $query2->have_posts() ) {

    echo '<ul class="more-posts">';
    
        // Start looping over the query results.
        while ( $query2->have_posts() ) {

            $query2->the_post();
    
            ?>

            <li <?php post_class(); ?>>
                <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
                    <?php the_title(); ?>
                </a>
            </li>
    
            <?php
    
        }
    
    echo '</ul>';

}

// Restore original post data.
wp_reset_postdata();

?>

我在這裡使用了兩個關鍵參數:

  • 'posts_per_page' => '1',與第一個查詢一起使用,僅輸出最新的帖子。
  • 'offset' = '1',與第二個查詢一起使用,跳過第一個帖子,確保它不會在下面的列表中重複。

從上面的程式碼可以看出,每個查詢的循環略有不同。第一個輸出特色圖像、標題和摘錄,而第二個檢查查詢是否有帖子,如果有,則打開ul 元素,並將每個帖子標題包含在li元素及其頁面的連結。

您也會注意到我在兩個循環之後使用了 wp_reset_postdata() 。如果我沒有這樣做,那麼在輔助循環之外使用模板標籤將為我提供有關循環內最後一篇文章的數據。呼叫此函數會將發布資料重置到主查詢。

訪問循環內的帖子資訊

您可以在循環內呼叫許多函數來存取有關當前帖子的資訊。您也已經看到本教程中使用了其中一些。在本節中,我將向您列出一些您可能偶爾會使用的常用功能。

取得標題

您可以使用三個函數來取得貼文的標題。它們是 the_title()get_the_title()the_title_attribute()get_the_title() 函數只是檢索貼文標題,而 the_title() 將根據傳遞的參數顯示或檢索標題以及可選標記。當您想要在顯示標題之前對其進行清理時,您應該使用 the_title_attribute()

取得摘錄或完整內容

有一個名為 the_excerpt() 的專用函數來顯示目前貼文的摘錄。它將多個過濾器應用於所提供的摘錄,以便可以正確地向觀眾顯示。並非每篇文章都會有作者提供的摘錄。在這種情況下,它會在顯示之前產生完整帖子摘錄的精簡版本。

您可以使用函數 the_content() 顯示貼文的完整內容。

取得貼文類別、標籤和其他元資料

您的 WordPress 貼文通常會有您指派的一些標籤或類別。您可以使用 the_tags()the_category() 函數在迴圈中顯示這些標籤和類別的清單。使用 the_author() 函數顯示貼文的作者。帖子的 ID 也可以透過函數 the_ID() 來存取。

取得發布或修改日期和時間

WordPress 中有專用函數,您可以在循環中使用它們來顯示帖子的發布日期 (the_date()) 和時間 (the_time())。您應該記住的兩個重要點是 the_time() 也可以用於僅顯示帖子的發布日期。此外,對於同一天發布的多個帖子, the_date() 的輸出僅回顯一次。這基本上意味著您幾乎總是希望使用 the_time() 以獲得更大的靈活性和易用性。

摘要

如果沒有循環,WP_Query 並沒有真正做太多事情。這個循環是您用來顯示 WordPress 根據您的查詢參數從資料庫中取得的資料的程式碼。

如我所示範的,循環有一些變化。一個簡單的循環將按照您在查詢參數中指定的順序(或預設按日期降序)輸出所有帖子。如果將if( $query->have_posts() )while( $query->have_posts() ) 分開,您可以在循環外部插入額外的標記,但前提是您的查詢已傳回資料。最後,透過指定替代參數並在每次循環後使用 wp_reset_postdata(),您可以多次使用 WP_Query 在頁面上建立多個循環。

這篇文章已根據 Nitish Kumar 的貢獻進行了更新。 Nitish 是一名 Web 開發人員,擁有在各種平台上建立電子商務網站的經驗。他將業餘時間花在個人專案上,讓他的日常生活變得更輕鬆,或在晚上與朋友一起散步。

以上是掌握 WP_Query:利用循環的力量的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn