add_shortcode()

add_shortcode()函数是Wordpress函数,添加新的快捷方式。

add_shortcode( string $tag, callable $callback )

添加新的快捷方式。
Adds a new shortcode.

说明(Description)

应注意通过前缀或其他方式确保要添加的快捷方式标记是唯一的,并且不会与其他已添加的快捷方式标记冲突。如果标记重复,则以最后加载的标记为准。


参数(Parameters)

参数类型必填说明
$tag(string)必需要在文章内容中搜索的快捷方式标记。
$callback(callable)必需找到快捷方式时要运行的回调函数。默认情况下,每个shortcode回调都会传递三个参数,包括属性数组($atts)、shortcode content或null(如果未设置($content))以及shortcode标记本身($shortcode_tag)。

返回(Return)

无返回值


源码(Source)

/**
 * Add hook for shortcode tag.
 *
 * There can only be one hook for each shortcode. Which means that if another
 * plugin has a similar shortcode, it will override yours or yours will override
 * theirs depending on which order the plugins are included and/or ran.
 *
 * Simplest example of a shortcode tag using the API:
 *
 *     // [footag foo="bar"]
 *     function footag_func( $atts ) {
 *         return "foo = {
 *             $atts[foo]
 *         }";
 *     }
 *     add_shortcode( 'footag', 'footag_func' );
 *
 * Example with nice attribute defaults:
 *
 *     // [bartag foo="bar"]
 *     function bartag_func( $atts ) {
 *         $args = shortcode_atts( array(
 *             'foo' => 'no foo',
 *             'baz' => 'default baz',
 *         ), $atts );
 *
 *         return "foo = {$args['foo']}";
 *     }
 *     add_shortcode( 'bartag', 'bartag_func' );
 *
 * Example with enclosed content:
 *
 *     // [baztag]content[/baztag]
 *     function baztag_func( $atts, $content = '' ) {
 *         return "content = $content";
 *     }
 *     add_shortcode( 'baztag', 'baztag_func' );
 *
 * @since 2.5.0
 *
 * @global array $shortcode_tags
 *
 * @param string   $tag  Shortcode tag to be searched in post content.
 * @param callable $func Hook to run when shortcode is found.
 */
function add_shortcode($tag, $func) {
	global $shortcode_tags;
	$shortcode_tags[ $tag ] = $func;
}
更新版本源码位置使用被使用
2.5.0wp-includes/shortcodes.php:6322

笔记(Notes)

// [footag foo="bar"]
function wpdocs_footag_func( $atts ) {
    return "foo = {$atts['foo']}";
}
add_shortcode( 'footag', 'wpdocs_footag_func' );
class MyPlugin {
    public static function wpdocs_baztag_func( $atts, $content = "" ) {
        return "content = $content";
    }
}
add_shortcode( 'baztag', array( 'MyPlugin', 'wpdocs_baztag_func' ) );
function wpdocs_the_shortcode_func( $atts ) {
    $attributes = shortcode_atts( array(
        'title' => false,
        'limit' => 4,
    ), $atts );
     
    ob_start();
 
    // include template with the arguments (The $args parameter was added in v5.5.0)
    get_template_part( 'template-parts/wpdocs-the-shortcode-template', null, $attributes );
 
    return ob_get_clean();
 
}
add_shortcode( 'wpdocs_the_shortcode', 'wpdocs_the_shortcode_func' );
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索