add_shortcode() 这个短代码函数还是很常见的,我们可以设置WordPress的短代码实现快捷显示需要的功能和内容。这个短代码是WordPress 提供的一个非常重要的函数,用于在文章、页面或其他支持短代码(Shortcode)的内容中插入自定义功能或动态内容。通过它,开发者可以轻松地创建自己的短代码,让非技术人员也能在编辑器中插入复杂的功能,而无需编写代码。
函数原型:
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, 张三!
本文出处:老蒋部落 » WordPress add_shortcode() 函数使用方法 | 欢迎分享( 公众号:老蒋朋友圈 )