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

WP中ACF作者字段查询无结果问题:代码排查求助

解决ACF作者字段查询无结果的问题

可能的原因及解决办法

  • ACF字段存储类型不匹配
    如果你的「author」字段是用户选择类型,ACF默认存储的是用户ID而非姓名文本,用页面标题(姓名)匹配自然查不到结果:

    1. 先通过页面标题获取对应用户ID:
      $user = get_user_by('display_name', $title);
      $user_id = $user ? $user->ID : 0;
      
    2. 将meta_query中的value替换为$user_id,compare改为=(因为存储的是精确ID)。

    如果是文本字段,检查ACF存储的姓名和页面标题是否完全一致(比如空格、大小写、特殊符号差异),细微差别都会导致LIKE匹配失败。

  • get_posts参数不规范

    • 原代码中category参数建议替换为cat,这是get_posts更常用的分类参数写法;
    • 如果你的文章是自定义文章类型,必须添加'post_type' => '你的自定义类型标识',否则默认只查询post类型文章。
  • 调试排查
    加入调试代码定位问题:

    1. 打印当前页面标题,确认取值正确:
      var_dump($title);
      
    2. 打印最终执行的SQL语句,直观查看查询逻辑:
      global $wpdb;
      echo $wpdb->last_query;
      

修改后的示例代码

文本字段场景

function hide_cotw_heading(){
    $title = get_the_title();
    // 调试用:确认标题值
    // var_dump($title);

    $latest_posts = get_posts( array(
        'cat' => 9,
        'post_type' => 'post', // 自定义类型请替换
        'meta_query' => array(
            'relation' => 'OR',
            array(
                'key'     => 'author_1',
                'value'   => $title,
                'compare' => 'LIKE',
            ),
            array(
                'key'     => 'author_2',
                'value'   => $title,
                'compare' => 'LIKE',
            ),
        )
    ) );

    // 调试用:打印SQL语句
    // global $wpdb;
    // echo $wpdb->last_query;

    return $latest_posts ? 'Has posts' : 'No posts';
}

用户字段场景

function hide_cotw_heading(){
    $title = get_the_title();
    // 通过姓名获取用户ID
    $user = get_user_by('display_name', $title);
    if (!$user) {
        return 'No posts';
    }
    $user_id = $user->ID;

    $latest_posts = get_posts( array(
        'cat' => 9,
        'post_type' => 'post', // 自定义类型请替换
        'meta_query' => array(
            'relation' => 'OR',
            array(
                'key'     => 'author_1',
                'value'   => $user_id,
                'compare' => '=',
            ),
            array(
                'key'     => 'author_2',
                'value'   => $user_id,
                'compare' => '=',
            ),
        )
    ) );

    return $latest_posts ? 'Has posts' : 'No posts';
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 11:07:30