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

如何检测包含参数(含id属性)的Shortcode是否存在及在网站生效?

嘿,我来帮你搞定这两个Shortcode检测的问题:

一、先确认目标Shortcode是否已被注册激活

如果只是想知道shortcode这个标签有没有在你的WordPress站点中被注册启用,直接用官方提供的shortcode_exists()函数就可以了,用法很简单:

// 检测名为"shortcode"的短代码是否存在
if ( shortcode_exists( 'shortcode' ) ) {
    echo "这个Shortcode已经被激活注册啦";
} else {
    echo "站点里还没注册这个Shortcode";
}

这个函数只检查该Shortcode的标签是否被注册,不管它带什么参数,只要对应的注册函数存在就会返回true。

二、检测内容中是否存在带特定'id'参数的Shortcode

如果要精准查找像[shortcode id="3268"]这种带特定id参数的Shortcode是否出现在内容里,就需要结合正则和参数解析来做了,毕竟shortcode_exists()不管参数细节。

这里给你一个靠谱的实现方式,适配WordPress的Shortcode规则(比如参数的单引号、双引号、空格等情况):

// 假设你要检查某篇文章的内容,先获取内容($post_id替换成你要检查的文章ID)
$content = get_post_field( 'post_content', $post_id );
$target_shortcode_tag = 'shortcode';
$target_id = '3268';

$found_target = false;
// 使用WordPress自带的Shortcode正则,比自己写的更准确
$shortcode_regex = get_shortcode_regex();

// 匹配内容中所有的Shortcode
preg_match_all( $shortcode_regex, $content, $all_shortcodes, PREG_SET_ORDER );

foreach ( $all_shortcodes as $sc_match ) {
    // 先匹配Shortcode标签是否是我们要找的
    if ( $sc_match[2] === $target_shortcode_tag ) {
        // 解析这个Shortcode的参数
        $sc_atts = shortcode_parse_atts( $sc_match[3] );
        // 检查是否存在id参数,且值等于目标id
        if ( isset( $sc_atts['id'] ) && trim( $sc_atts['id'] ) === $target_id ) {
            $found_target = true;
            break; // 找到就停止遍历
        }
    }
}

// 根据结果做后续处理
if ( $found_target ) {
    echo "找到了带id='3268'的[shortcode]!";
} else {
    echo "没找到目标Shortcode";
}

额外提示

如果要检查整个站点所有内容里是否存在这个Shortcode,你可以遍历所有文章、页面甚至自定义文章类型,但要注意性能问题——如果站点内容很多,直接遍历所有内容会很慢。这种情况下可以用$wpdb做数据库层面的模糊查询,比如:

global $wpdb;
$target_id = '3268';
// 搜索post_content中包含"[shortcode id=\"3268\"]"的内容(注意转义引号)
$results = $wpdb->get_results(
    $wpdb->prepare(
        "SELECT ID FROM {$wpdb->posts} WHERE post_content LIKE %s AND post_status = 'publish'",
        '%[shortcode id="' . $target_id . '"]%'
    )
);

if ( !empty( $results ) ) {
    echo "站点中存在带该id的Shortcode,涉及的文章ID有:" . implode( ', ', wp_list_pluck( $results, 'ID' ) );
} else {
    echo "站点里没找到目标Shortcode";
}

不过这种方式只能匹配完全一致的格式(比如双引号的id),如果有用户用单引号或者无引号的写法,可能漏检,所以如果要覆盖所有情况,还是结合前面的正则解析更稳妥,只是效率稍低。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:29:16