You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress归档页面无法正确获取文章作者ID的开发问题求助

WordPress归档页获取当前循环文章作者ID方案

问题根源

你始终拿到归档页本身作者ID,本质是上下文读取错误:

  • 获取作者ID的代码放错了位置:要么在主循环外面,要么在循环内the_post()执行之前,此时全局$post对象指向的是归档页本身这个页面的post数据,还没切换到当前遍历的文章
  • 如果归档页里写了自定义WP_Query查询,循环结束后没调用wp_reset_postdata()重置全局对象,会污染后续所有依赖全局post的数据读取

你之前试的global $post; $author_id = $post->post_author;写法本身没有语法错误,只要放对位置就能拿到正确值。

正确实现步骤

1. 把数据读取代码放到主循环的正确位置

所有读取当前文章数据的逻辑,必须放在主循环的the_post()调用之后,标准结构参考:

<?php
// 归档页主循环
if ( have_posts() ) :
    while ( have_posts() ) : the_post(); 
    // 执行完上面这行,全局$post才会切换到当前遍历到的文章,这里开始写你的业务代码
    // 显式传入当前文章ID读取作者,容错率最高,避免全局污染导致的错误
    $author_id = get_the_author_meta('ID', get_the_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 );

    if( empty($dealer_name)) {
        $user = get_userdata( $author_id ); 
        $dealer_name = $user->user_nicename;
    }
    ?>
    <!-- 前端输出部分 -->
    <div class="dealer-informatie">
        <h4 class="dealer-titel"><?php echo $vehicle_location_name; ?></h4>
        当前文章作者ID: <?php echo $author_id; ?><br>
        电话: <?php echo $vehicle_location_phone; ?><br>
        邮箱: <?php echo $vehicle_location_email; ?><br>
        地址: <?php echo $vehicle_location_address; ?>
    </div>
    <?php
    endwhile;
    // 分页逻辑可以放这里
endif;
?>

2. 自定义查询必须重置全局对象

如果你在归档页中用了自定义WP_Query做额外的内容查询,循环结束后一定要加重置代码,否则全局$post对象会停留在自定义查询的最后一篇文章,导致后续数据读错:

<?php
// 自定义查询示例
$custom_args = array(
    // 你的查询参数
);
$custom_query = new WP_Query($custom_args);
if($custom_query->have_posts()){
    while($custom_query->have_posts()){
        $custom_query->the_post();
        // 自定义循环内的内容输出
    }
    wp_reset_postdata(); // 这行必须加,把全局$post切回主循环的当前文章
}
?>

3. 避坑提示

  • 不要在循环外调用get_the_author_meta()、读取$post->post_author这类依赖全局上下文的函数,循环外没有“当前文章”的概念,读出来的默认都是当前页面本身的数据
  • 调用get_the_author_meta()时显式传入get_the_ID()作为第二个参数,比不传参的写法容错率高很多,哪怕全局对象被轻微污染也能读到正确的作者ID

内容的提问来源于stack exchange,提问作者user2958073

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 01:09:19