問題描述

WP Codex says 這樣做:

// You wish to make $my_var available to the template part at `content-part.php`
set_query_var( 'my_var', $my_var );
get_template_part( 'content', 'part' );

但是如何在 echo $my_var 內部模板部分? get_query_var($my_var)不適合我。

我已經看到了使用 locate_template 的大量建議。那是最好的方式嗎?

最佳解決方案

由於帖子透過 the_post()(分別透過 setup_postdata()) 設定資料,因此可以透過 API(get_the_ID()) 進行訪問,例如,我們假設我們迴圈使用一組使用者 (如 setup_userdata()填充當前登入的全域性變數使用者,對此任務無效),並嘗試顯示每個使用者的後設資料:

<?php
get_header();

// etc.

// In the main template file
$users = new WP_User_Query( [ ... ] );

foreach ( $users as $user )
{
    set_query_var( 'user_id', absint( $user->ID ) );
    get_template_part( 'template-parts/user', 'contact_methods' );
}

然後,在我們的 wpse-theme/template-parts/user-contact_methods.php 檔案中,我們需要訪問使用者 ID:

<?php
/** @var int $user_id */
$some_meta = get_the_author_meta( 'some_meta', $user_id );
var_dump( $some_meta );

而已。

這個解釋實際上正好在您在問題中引用的部分:

However, load_template(), which is called indirectly by get_template_part() extracts all of the WP_Query query variables, into the scope of the loaded template.

本機 PHP extract()函式”extracts” 的變數 (global $wp_query->query_vars 屬性),並將每個部分放入其自己的變數中,該變數具有與該鍵完全相同的名稱。換一種說法:

set_query_var( 'foo', 'bar' );

$GLOBALS['wp_query'] (object)
    -> query_vars (array)
        foo => bar (string 3)

extract( $wp_query->query_vars );

var_dump( $foo );
// Result:
(string 3) 'bar'

次佳解決方案

humanmadehm_get_template_part 功能非常好,我一直使用它。

你打電話

hm_get_template_part( 'template_path', [ 'option' => 'value' ] );

然後在你的模板中,你使用

$template_args['option'];

返回值。它有快取和一切,雖然你可以採取,如果你喜歡。

您甚至可以透過將'return' => true 傳遞到鍵/值陣列來返回渲染的模板作為字串。

/**
 * Like get_template_part() put lets you pass args to the template file
 * Args are available in the tempalte as $template_args array
 * @param string filepart
 * @param mixed wp_args style argument list
 */
function hm_get_template_part( $file, $template_args = array(), $cache_args = array() ) {
    $template_args = wp_parse_args( $template_args );
    $cache_args = wp_parse_args( $cache_args );
    if ( $cache_args ) {
        foreach ( $template_args as $key => $value ) {
            if ( is_scalar( $value ) || is_array( $value ) ) {
                $cache_args[$key] = $value;
            } else if ( is_object( $value ) && method_exists( $value, 'get_id' ) ) {
                $cache_args[$key] = call_user_method( 'get_id', $value );
            }
        }
        if ( ( $cache = wp_cache_get( $file, serialize( $cache_args ) ) ) !== false ) {
            if ( ! empty( $template_args['return'] ) )
                return $cache;
            echo $cache;
            return;
        }
    }
    $file_handle = $file;
    do_action( 'start_operation', 'hm_template_part::' . $file_handle );
    if ( file_exists( get_stylesheet_directory() . '/' . $file . '.php' ) )
        $file = get_stylesheet_directory() . '/' . $file . '.php';
    elseif ( file_exists( get_template_directory() . '/' . $file . '.php' ) )
        $file = get_template_directory() . '/' . $file . '.php';
    ob_start();
    $return = require( $file );
    $data = ob_get_clean();
    do_action( 'end_operation', 'hm_template_part::' . $file_handle );
    if ( $cache_args ) {
        wp_cache_set( $file, $data, serialize( $cache_args ), 3600 );
    }
    if ( ! empty( $template_args['return'] ) )
        if ( $return === false )
            return false;
        else
            return $data;
    echo $data;
}

第三種解決方案

我正在環顧四周,並找到了各種各樣的答案。它似乎在本機級別,Wordpress 確實允許在模板部分訪問變數。我確實發現使用 include 與 locate_template 配合使得可以在檔案中訪問變數範圍。

include(locate_template('your-template-name.php'));

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。