插件开发文档

基础短代码

💡 云策文档标注

概述

本文档介绍了如何使用 Shortcode API 在 WordPress 中添加、移除和检查短代码,包括注册回调函数和基本操作流程。

关键要点

  • 使用 add_shortcode() 注册短代码,需指定短代码标签和回调函数。
  • 使用 remove_shortcode() 移除已注册的短代码,需确保短代码已注册并注意优先级。
  • 使用 shortcode_exists() 检查短代码是否已注册。

代码示例

add_shortcode('wporg', 'wporg_shortcode');
function wporg_shortcode( $atts = [], $content = null) {
    // do something to $content
    // always return
    return $content;
}

注意事项

  • 移除短代码前需确认其已注册,可通过调整 add_action() 优先级或使用较晚触发的 action hook 来确保。

📄 原文内容

Add a Shortcode

It is possible to add your own shortcodes by using the Shortcode API. The process involves registering a callback $func to a shortcode $tag using add_shortcode().

add_shortcode(
    string $tag,
    callable $func
);

[wporg] is your new shortcode. The use of the shortcode will trigger the wporg_shortcode callback function.

add_shortcode('wporg', 'wporg_shortcode');
function wporg_shortcode( $atts = [], $content = null) {
    // do something to $content
    // always return
    return $content;
}

Remove a Shortcode

It is possible to remove shortcodes by using the Shortcode API. The process involves removing a registered $tag using remove_shortcode() .

remove_shortcode(
    string $tag
);

Make sure that the shortcode have been registered before attempting to remove. Specify a higher priority number for add_action() or hook into an action hook that is run later.

Check if a Shortcode Exists

To check whether a shortcode has been registered use shortcode_exists().