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

使用ACF的WP_Query短代码问题:用户无法匹配自定义字段

短代码排查及修复方案

以下是导致代码返回"No results were found"的核心问题及修复方案:

  • 未获取当前用户ID:代码直接使用$current_user->ID,但未初始化当前用户对象。可直接用get_current_user_id()函数获取登录用户ID,无需额外声明全局变量。
  • WP_Query参数误用:numberposts是get_posts()的专属参数,WP_Query中需用posts_per_page设置显示所有文章(值设为-1)。
  • 缺少登录校验逻辑:未判断用户是否登录,未登录用户执行查询时会用0作为用户ID,自然查不到结果,需先校验登录状态。
  • HTML实体转义冗余:输出的HTML标签用了实体转义(如<),直接使用正常HTML标签更易维护,避免转义错误。

修复后的完整代码

add_shortcode( 'show_profile_posts', 'profile_posts' );
function profile_posts( $atts ) {
    $output = '';

    // 检查用户是否登录
    if ( !is_user_logged_in() ) {
        $output .= '<div class="fe-query-results-shortcode-output-none">请先登录查看内容</div>';
        return $output;
    }

    $current_user_id = get_current_user_id();
    $args = array(
        'posts_per_page' => -1,
        'post_type'      => 'profile',
        'meta_query'     => array(
            array(
                'key'     => 'user_id',
                'value'   => $current_user_id,
                'compare' => '='
            )
        )
    );

    $fe_query = new WP_Query( $args );

    if ( $fe_query->have_posts() ) {
        $output .= '<ul class="fe-query-results-shortcode-output">';
            while ( $fe_query->have_posts() ) {
                $fe_query->the_post();
                $title = get_the_title();
                $link = get_the_permalink();
                $output .= "<li><a href=\"{$link}\">{$title}</a></li>";
            }
        $output .= '</ul>';
    } else {
        $output .= '<div class="fe-query-results-shortcode-output-none">No results were found</div>';
    }

    wp_reset_postdata();
    return $output;
}

额外说明

  • 建议用meta_query替代单独的meta_key和meta_value,这是WP_Query更规范的自定义字段查询写法,兼容性更好。
  • 确认ACF后台设置的自定义字段名称确实为user_id,如果字段名不符,需同步修改代码中的key值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 09:40:57