WordPress开发函数add_shortcode(),添加一个新的短码。

用法:

add_shortcode( string $tag, callable $callback )

描述:

应该注意通过前缀或其他方法来确保所添加的shortcode标签是唯一的,不会与其他已经添加的shortcode标签冲突。在重复标记的情况下,最后加载的标记将优先。

参数:

$tag

(string) (必需) Shortcode标签要在帖子内容中搜索。

$callback

(callable) (必需) 找到短代码时要运行的回调函数。默认情况下,每个shortcode回调函数被传递三个参数,包括一个属性数组($atts), shortcode内容,如果没有设置则为null ($content),最后是shortcode标签本身($shortcode_tag),按照这个顺序。

更多信息

shortcode回调函数将被传递三个参数:shortcode属性、shortcode内容(如果有的话)和shortcode的名称。

每个短代码只能有一个钩子。这意味着如果另一个插件有类似的短代码,它会覆盖你的,或者你的插件会覆盖他们的,这取决于插件被包含和/或运行的顺序。

Shortcode属性名称在传递给处理程序函数之前总是转换为小写。值是不变的。

请注意,shortcode调用的函数不应该产生任何类型的输出。Shortcode函数应该返回用于替换Shortcode的文本。直接产生输出将会导致意想不到的结果。这类似于筛选器函数的行为方式,因为它们不应该从调用中产生预期的副作用,因为您无法控制从何时何地调用它们。

来源:

文件: wp-includes/shortcodes.php

function add_shortcode( $tag, $callback ) {

global $shortcode_tags;

if ( '' === trim( $tag ) ) {

$message = __( 'Invalid shortcode name: Empty name given.' );

_doing_it_wrong( __FUNCTION__, $message, '4.4.0' );

return;

}

if ( 0 !== preg_match( '@[<>&/[]x00-x20=]@', $tag ) ) {

/* translators: 1: Shortcode name, 2: Space-separated list of reserved characters. */

$message = sprintf( __( 'Invalid shortcode name: %1$s. Do not use spaces or reserved characters: %2$s' ), $tag, '& / < > [ ] =' );

_doing_it_wrong( __FUNCTION__, $message, '4.4.0' );

return;

}

$shortcode_tags[ $tag ] = $callback;

}

更新日志:
WordPress开发函数add_shortcode() (https://www.wpzt.net/) WordPress开发教程 第1张
用户贡献的笔记

(由Codex - 6年前贡献)

例子

使用API的一个简单的短代码标签示例:[footag foo="bar"]

add_shortcode( 'footag', 'wpdocs_footag_func' );

function wpdocs_footag_func( $atts ) {

return "foo = {$atts['foo']}";

}

一个很好的属性默认值的例子: [bartag foo="bar"]

add_shortcode( 'bartag', 'wpdocs_bartag_func' );

function wpdocs_bartag_func( $atts ) {

$atts = shortcode_atts( array(

'foo' => 'no foo',

'baz' => 'default baz'

), $atts, 'bartag' );

return "foo = {$atts['foo']}";

}

包含内容的示例:[baztag]content[/baztag]

add_shortcode( 'baztag', 'wpdocs_baztag_func' );

function wpdocs_baztag_func( $atts, $content = "" ) {

return "content = $content";

}

如果你的插件被设计成一个类,可以这样写:

add_shortcode( 'baztag', array( 'MyPlugin', 'wpdocs_baztag_func' ) );

class MyPlugin {

public static function wpdocs_baztag_func( $atts, $content = "" ) {

return "content = $content";

}

}

(由dingo-d - 1年前贡献)

当在插件中添加' add_shortcode() '函数时,最好将其添加到' init '挂钩的函数中。这样wordpress就有时间进行正确的初始化。

add_action( 'init', 'wpdocs_add_custom_shortcode' );

function wpdocs_add_custom_shortcode() {

add_shortcode( 'footag', 'wpdocs_footag_func' );

}

正如插件手册中描述的那样。

(由Patrick Johanneson贡献- 3年前)

注释(来自法典- https://codex.wordpress.org/Function_Reference/add_shortcode#Notes)

  • shortcode回调函数将被传递三个参数:shortcode属性、shortcode内容(如果有的话)和shortcode的名称。
  • 每个短代码只能有一个钩子。这意味着如果另一个插件有类似的短代码,它将覆盖你的或你的将覆盖他们的取决于插件的顺序被包含和/或运行。
  • Shortcode属性名称在传递给处理程序函数之前总是转换为小写。值是不变的。
  • 请注意,shortcode调用的函数不应该产生任何类型的输出。Shortcode函数应该返回用于替换Shortcode的文本。直接产生输出将会导致意想不到的结果。这类似于筛选器函数的行为方式,因为它们不应该从调用中产生预期的副作用,因为您无法控制从何时何地调用它们。