
在 WordPress 归档页(如自定义查询的汽车列表页)中,若直接调用 get_the_author_meta('ID') 或 $post->post_author 无法获取预期作者 ID,根本原因在于未正确设置全局 $post 上下文——必须通过 WP_Query 的 the_post() 方法激活“主循环”状态,才能使所有 the_* 和 get_the_* 函数正常工作。
在 wordpress 归档页(如自定义查询的汽车列表页)中,若直接调用 `get_the_author_meta('id')` 或 `$post->post_author` 无法获取预期作者 id,根本原因在于未正确设置全局 `$post` 上下文——必须通过 `wp_query` 的 `the_post()` 方法激活“主循环”状态,才能使所有 `the_*` 和 `get_the_*` 函数正常工作。
当你在 archive 页面(例如展示多个汽车条目的列表页)中使用自定义 WP_Query 时,WordPress 的全局 $post 对象并不会自动切换为当前查询中的每篇文章。因此,像 get_the_author_meta('ID')、get_the_author() 这类依赖全局上下文的函数,会始终返回当前页面(如归档页本身)的作者 ID(通常是管理员),而非循环内每篇文章的真实作者。
✅ 正确做法是:显式调用 $query->the_post(),它不仅移动内部指针,更关键的是将当前文章数据设置为全局 $post,并触发 setup_postdata(),从而让所有模板标签(包括 get_the_author_meta())准确指向当前文章的作者。
以下是推荐的完整实现结构:
<?php // 构建你的查询参数(示例)
$search_args = array(
'post_type' => 'car',
'posts_per_page' => 12,
'post_status' => 'publish'
);
$cars_query = new WP_Query($search_args);
if ($cars_query->have_posts()) :
while ($cars_query->have_posts()) :
$cars_query->the_post(); // ✅ 关键:激活当前文章上下文
// 现在可安全获取当前文章作者 ID
$author_id = get_the_author_meta('ID');
// 获取自定义用户元字段
$dealer_name = get_user_meta($author_id, 'dealer_name', true);
$office_phone = get_user_meta($author_id, 'office_phone', true);
$dealer_address = get_user_meta($author_id, 'dealer_address', true);
$dealer_address_latitude = get_user_meta($author_id, 'dealer_address_latitude', true);
$dealer_address_longitude = get_user_meta($author_id, 'dealer_address_longitude', true);
// 回退逻辑:若 dealer_name 为空,使用用户昵称
if (empty($dealer_name)) {
$user = get_userdata($author_id);
$dealer_name = $user ? $user->user_nicename : '未知经销商';
}
// 输出 HTML(注意:此处 $vehicle_location_* 应来自 post meta 或关联数据)
?>
<div class="dealer-informatie">
<h4 class="dealer-titel"><?php echo esc_html(get_the_title()); ?></h4>
authorid of post: <?php echo (int) $author_id; ?><br>
Telefoon: <?php echo esc_html($office_phone); ?><br>
E-mail: <?php echo esc_html(get_post_meta(get_the_ID(), 'vehicle_location_email', true)); ?><br>
Adres: <?php echo esc_html($dealer_address); ?>
</div>
<?php endwhile;
// ✅ 必须重置全局 post 数据,避免影响后续主循环(如页脚、侧边栏)
wp_reset_postdata();
else :
echo '<p>暂无车辆信息。';
endif;
?>
⚠️ 重要注意事项:
- ❌ 避免在 while 循环外或未调用 the_post() 前使用 get_the_author_meta();
- ❌ 不要混用 foreach ($cars as $car) 与 get_the_author_meta() —— 它们不兼容;
- ✅ 所有基于 the_ 前缀的函数(如 the_title()、the_content())和 get_the_* 函数均依赖 the_post() 设置的上下文;
- ✅ wp_reset_postdata() 是强制性收尾操作,否则可能导致后续模板区域(如 get_sidebar())显示错误内容;
- ? 始终对输出内容进行转义(如 esc_html()),防止 XSS 漏洞。
通过严格遵循「查询 → have_posts() → the_post() → 获取数据 → 重置」这一流程,即可稳定、准确地在任意自定义循环中获取每篇文章的真实作者 ID 及其扩展元数据。











