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

WordPress中ACF字段判断的短代码函数语法错误求助

WordPress ACF短代码语法错误修复方案

你的代码存在三处语法问题,导致保存报错:

  • 混用了PHP替代语法(if:)与常规大括号{},替代语法不需要额外加大括号
  • 替代语法的if结构未用endif;闭合
  • add_shortcode语句末尾缺少分号;

修正后的代码如下(保留替代语法写法):

// 当ACF字段值不为"not found"时输出内容的短代码
function show_alliance() {
    $alliance = get_field('field_6383d4b46deed');

    if ($alliance != 'not found'):
        return '<h2>TITLE</h2><p>This is... '. $alliance .' </p>';
    else:
        return '';
    endif;
}

add_shortcode('alliance', 'show_alliance');

也可以改用更通用的常规大括号写法:

// 当ACF字段值不为"not found"时输出内容的短代码
function show_alliance() {
    $alliance = get_field('field_6383d4b46deed');

    if ($alliance != 'not found') {
        return '<h2>TITLE</h2><p>This is... '. $alliance .' </p>';
    } else {
        return '';
    }
}

add_shortcode('alliance', 'show_alliance');

两种写法都能实现需求:获取指定ACF字段值,若值不等于"not found"则输出H2标题和包含字段内容的段落,否则不输出任何内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 17:45:32