函数原型:
add_shortcode( $tag, $callback );$tag(字符串):短代码的名称,也就是你在文章中使用的标签,比如 [my_shortcode] 中的 my_shortcode。
$callback(可调用对象):当 WordPress 解析到这个短代码时调用的 PHP 函数。这个函数负责返回要插入到文章中的内容。
基本用法:
假设我们想创建一个短代码 [hello],当在文章中使用它时,会显示 "Hello, World!"。
// 在主题的 functions.php 文件中添加以下代码
function hello_shortcode() {
return 'Hello, World!';
}
add_shortcode( 'hello', 'hello_shortcode' );这样,我们在文章中插入 [hello],会显示 Hello, World!。
也可以设置带参数的短代码。这样更灵活。比如创建一个 [greet name="张三"] 的短代码,显示 "Hello, 张三!"。
function greet_shortcode( $atts ) {
// 设置默认参数
$atts = shortcode_atts( array(
'name' => 'World', // 默认名字是 World
), $atts );
return 'Hello, ' . esc_html( $atts['name'] ) . '!';
}
add_shortcode( 'greet', 'greet_shortcode' );效果:
[greet] → Hello, World!
[greet name="张三"] → Hello, 张三!