在WordPress中创建自定义短代码是通过使用shortcode API来实现的。以下是一个简单的步骤指南,展示如何创建一个自定义短代码:
步骤 1: 添加短代码处理函数
首先,你需要在你的插件文件或者主题的 functions.php
文件中定义一个函数,这个函数将处理短代码的内容。
function my_custom_shortcode($atts, $content = null) {
// 短代码的属性可以通过 $atts 数组访问
// $content 是短代码包围的内容
// 解析属性
extract(shortcode_atts(array(
'title' => '默认标题', // 默认值
), $atts));
// 创建返回的HTML内容
$output = '<h2>' . esc_html($title) . '</h2>';
if ($content) {
$output .= '<p>' . do_shortcode($content) . '</p>';
}
return $output;
}
步骤 2: 添加短代码
接下来,你需要使用 add_shortcode
函数来注册你的自定义短代码处理函数。
add_shortcode('my_shortcode', 'my_custom_shortcode');
在上面的代码中,'my_shortcode'
是你自定义短代码的名字,'my_custom_shortcode'
是处理短代码的函数名。
步骤 3: 使用短代码
现在,你可以在WordPress的文章、页面或小工具中使用你的自定义短代码了。例如:
[my_shortcode title="这是自定义标题"]
这是短代码的内容。
[/my_shortcode]
这将在页面上显示一个标题为“这是自定义标题”的二级标题,以及一个段落包含“这是短代码的内容。”
完整示例
以下是完整的代码示例,你可以将其添加到你的插件或主题的 functions.php
文件中:
// 短代码处理函数
function my_custom_shortcode($atts, $content = null) {
// 解析属性
extract(shortcode_atts(array(
'title' => '默认标题', // 默认值
), $atts));
// 创建返回的HTML内容
$output = '<h2>' . esc_html($title) . '</h2>';
if ($content) {
$output .= '<p>' . do_shortcode($content) . '</p>';
}
return $output;
}
// 注册短代码
add_shortcode('my_shortcode', 'my_custom_shortcode');
保存文件后,你就可以在WordPress的编辑器中使用 [my_shortcode]
短代码了。记得在激活插件或更新 functions.php
文件后,你可能需要刷新页面或重新加载WordPress来使短代码生效。