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

如何在WordPress现有短代码中传入URL提取的match_id参数?

问题描述

在WordPress中已配置自定义固定链接格式为/match/%match_id%/,需从site.com/match/2/这类URL中提取match_id(示例值为2,支持任意数字),并将其作为参数传入现有短代码(如[fp-predictions text="No data" match=[match_id]])。

已实现[match_id]短代码可正常输出match_id,但无法通过嵌套写法将值传递给其他短代码,现有代码如下:

function get_match_id_from_url() {
    global $wp;
    $current_url = home_url(add_query_arg(array(), $wp->request));
    $parts = explode('/', $current_url);
    $match_id = end($parts);
    return $match_id;
}
function display_match_id_shortcode() {
    $match_id = get_match_id_from_url();
    return $match_id;
}
add_shortcode('match_id', 'display_match_id_shortcode');
解决方案

1. 优化match_id获取方式(推荐)

手动解析URL的方式易受格式变化影响,利用WordPress内置查询变量更可靠:

步骤1:注册查询变量

若尚未注册match_id作为查询变量,添加以下代码:

function register_match_id_query_var($vars) {
    $vars[] = 'match_id';
    return $vars;
}
add_filter('query_vars', 'register_match_id_query_var');

步骤2:简化match_id获取函数

替换原有get_match_id_from_url函数,直接通过查询变量获取:

function get_match_id() {
    return get_query_var('match_id', 0); // 未获取到值时返回默认值0
}

2. 解决短代码嵌套传递问题

WordPress默认不解析短代码内部的嵌套短代码,可通过以下两种方式处理:

方式A:创建包装短代码

编写一个自动注入match_id的包装短代码,直接调用原短代码逻辑:

function fp_predictions_auto_shortcode($atts) {
    $match_id = get_match_id();
    // 合并用户传入的属性与自动获取的match_id
    $atts = shortcode_atts([
        'text' => 'No data',
        'match' => $match_id
    ], $atts);
    // 调用[fp-predictions]对应的处理函数(需替换为实际函数名)
    return fp_predictions_shortcode($atts);
}
add_shortcode('fp-predictions-auto', 'fp_predictions_auto_shortcode');

使用时直接写[fp-predictions-auto text="No data"]即可自动传入当前页面的match_id。

方式B:启用嵌套短代码解析

若希望保留嵌套写法,添加以下代码让WordPress递归解析所有嵌套短代码:

function recursive_do_shortcode($content) {
    $processed = do_shortcode($content);
    return $processed !== $content ? recursive_do_shortcode($processed) : $processed;
}
add_filter('the_content', 'recursive_do_shortcode', 11); // 优先级高于默认的do_shortcode

之后使用[fp-predictions text="No data" match="[match_id]"](注意[match_id]需加引号)即可正常解析。

3. 模板文件中直接调用

若在主题模板中使用,可直接获取match_id并拼接短代码:

$match_id = get_match_id();
echo do_shortcode("[fp-predictions text='No data' match='{$match_id}']");

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 05:13:10