remove_shortcode()
云策文档标注
概述
remove_shortcode() 函数用于移除已注册的短代码钩子,通过从全局变量 $shortcode_tags 中删除指定标签来实现。此函数自 WordPress 2.5.0 版本引入,适用于动态管理短代码的场景。
关键要点
- 函数接受一个必需参数 $tag,表示要移除的短代码标签。
- 通过 unset() 操作从全局数组 $shortcode_tags 中删除对应条目,从而取消短代码的解析。
- 常用于在特定条件下(如特定页面)动态禁用短代码,以提高灵活性和性能。
代码示例
// 移除单个短代码示例
add_action( 'init', 'remove_my_shortcodes', 20 );
function remove_my_shortcodes() {
remove_shortcode( 'myShortcode' );
}
// 在特定页面移除多个短代码示例
function prefix_remove_shortcode_trigger_on_specific_pages() {
$page_ids = array( 22, 2599 );
$shortcodes_to_remove = array( 'my_shortcode_1', 'someone_other_shortcode' );
if ( in_array( get_the_ID(), $page_ids ) ) {
foreach ( $shortcodes_to_remove as $shortcode_tag ) {
remove_shortcode( $shortcode_tag );
}
}
}
add_action( 'the_post', 'prefix_remove_shortcode_trigger_on_specific_pages', 20 );注意事项
- 移除短代码后,相关标签在内容中将不再被解析,可能影响页面显示,需确保在适当时机调用。
- 建议在 init 或 the_post 等 Hook 中使用,以避免与其他插件或主题的短代码冲突。
- 参数 $tag 必须与 add_shortcode() 注册时使用的标签完全一致,区分大小写。
原文内容
Removes hook for shortcode.
Parameters
$tagstringrequired-
Shortcode tag to remove hook for.
Source
function remove_shortcode( $tag ) {
global $shortcode_tags;
unset( $shortcode_tags[ $tag ] );
}
Changelog
| Version | Description |
|---|---|
| 2.5.0 | Introduced. |
Skip to note 3 content
Aurovrata Venet
//add a custom shortcode add_action( 'init', 'my_add_shortcodes' ); function my_add_shortcodes() { add_shortcode( 'myShortcode', 'my_shortcode_function' ); } //which can also remove add_action( 'init', 'remove_my_shortcodes',20 ); function remove_my_shortcodes() { remove_shortcode( 'myShortcode' ); }Skip to note 4 content
raoabid491
/** * Remove shortcodes if we are on some specific page */ function prefix_remove_shortcode_trigger_on_specific_pages() { // page ids where we want to remove shortcodes $page_ids = array( 22, 2599 ); // array of shortcode tags to be removed. $shortcodes_to_remove = array( 'my_shortcode_1', 'someone_other_shortcode' ); if ( in_array( get_the_ID(), $page_ids ) ) { foreach ( $shortcodes_to_remove as $shortcode_tag ) { remove_shortcode( $shortcode_tag ); } } } add_action( 'the_post', 'prefix_remove_shortcode_trigger_on_specific_pages', 20 );