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

如何在ACF选项页外访问其选项的子字段shop_url?

解决ACF选项页外访问shop_url子字段的方案

1. 直接从ACF全局选项读取字段

ACF选项页的字段是全局存储的,和当前页面上下文无关,你可以直接用ACF核心函数get_field()指定'option'参数来获取:

// 获取选项页中的featureBanners数组
$feature_banners = get_field('featureBanners', 'option');
// 获取bannerSetting字段
$banner_setting = get_field('bannerSetting', 'option');

拿到数组后,可根据当前页面URL匹配对应的横幅项,提取shop_url:

$current_page_url = get_permalink();
$target_shop_url = '';

foreach ($feature_banners as $banner) {
    if ($banner['url'] === $current_page_url) {
        $target_shop_url = $banner['shop_url'];
        break;
    }
}

2. 改造现有Twig函数适配全局场景

既然你已经在ArchiveHelperExtension.php里有get_feature_post_url函数,可以修改它,让它支持从ACF选项页全局匹配当前页面的shop_url:

public function get_feature_post_url($post_id = null) {
    // 无post_id传入时,从ACF选项页匹配当前页面
    if (!$post_id) {
        $feature_banners = get_field('featureBanners', 'option');
        $current_url = get_permalink();
        
        foreach ($feature_banners as $banner) {
            if ($banner['url'] === $current_url) {
                return $banner['shop_url'] ?: '';
            }
        }
        return '';
    }
    
    // 保留原有针对单篇文章的逻辑
    return get_field('shop_url', $post_id) ?: '';
}

之后在目标页面的Twig模板里,直接调用{{ get_feature_post_url() }}就能拿到对应横幅的shop_url,给按钮赋值即可。

3. Twig模板内直接匹配(需ACF函数支持)

如果你的Twig环境允许直接调用ACF函数,也可以在模板里直接遍历选项页字段,匹配当前页面URL:

{% set current_url = app.request.uri %}
{% set feature_banners = get_field('featureBanners', 'option') %}

{% for banner in feature_banners %}
    {% if banner.url == current_url %}
        <a href="{{ banner.shop_url }}" class="shop-now-btn">Shop Now</a>
    {% endif %}
{% endfor %}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 02:17:46