問題描述

我無法在循環之外獲取帖子作者 ID,以使 get_the_author_meta 正常工作。到目前為止,我已經嘗試過不同的方法:

1 。

$author_id=$post->post_author;

2 。

global $post;
$author_id=$post->post_author;

3 。

$post_tmp = get_post($post_id);
$author_id = $post_tmp->post_author;

4 。

$author_id = $posts[0]->post_author;

我需要作者 ID 將其傳遞給:

$address = get_the_author_meta('user_email', $author_id);

有什麼建議麼?

最佳解決方案

如果你知道這個帖子 ID,就是使用 WordPress 核心函數 get_post_field()來獲取發佈作者 ID 在循環之外的最簡單和最簡單的方法。

$post_author_id = get_post_field( 'post_author', $post_id );

如果您還不知道所在頁面的帖子 ID,那麼由於 WP 3.1 最簡單的做法是使用 get_queried_object_id()(在方法列表中查找它),甚至在循環之外。

$post_id = get_queried_object_id();

如果這些不適合您,那麼請詳細説明您嘗試運行代碼的位置,我們可以看到我們是否可以進一步幫助。

次佳解決方案

以下是獲取並獲取 WordPress 循環外的作者 ID 的方法:

<?php
global $post;
$author_id=$post->post_author;
?>

那麼有可能我們 the_author_meta

<?php
the_author_meta( 'user_nicename', $author_id );
?>

第三種解決方案

取決於你在哪裏如果你在一個單一的頁面 (例如,只顯示一個 {{Insert Post Type Here}}),你可以使用 get_queried_object,它將獲取 post 對象。

<?php
if (is_singular()) {
    $author_id = get_queried_object()->post_author;
    $address = get_the_author_meta('user_email', $author_id);
}

如果你在別的地方,可以使用全局 $wp_query 對象,並檢查其 $posts 屬性。這也應該在單個頁面上工作。

<?php
global $wp_query;
if (!empty($wp_query->posts)) {
    $author_id = $wp_query->posts[0]->post_author;
    $address = get_the_author_meta('user_email', $author_id);
}

您也可以只是”false start” 的循環,並回滾以獲取作者 ID 。這不會導致任何額外的數據庫命中等。 WordPress 一次 (在寫作時) 獲取所有帖子。 rewind_posts 只將當前帖子 (全局 $post) 對象重置為數組的開頭。不利的是,這可能導致 loop_start 動作比您想要的方式早一點 – 不是一件很大的事情,只是需要注意的事情。

<?php
// make sure you're at the beginning.
rewind_posts();

// start the loop
the_post();

// get what you need
$address = get_the_author_meta('user_email');

// back to normal
rewind_posts();

參考文獻

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