1、定义双标签
开发过程:
步骤#1:定义一个函数,专门用于处理数据。
步骤#2:注册我们的短代码标记。实质上就是,告诉wordpress你要帮我处理哪个标记,然后用哪个函数的代码去处理。
步骤#3:在合适的实际,去注册短代码标记。
?php
functionshortcode_handler(atts=array(),content=null,tag=)
{
//如果你的短代码支持属性,需要以下代码,将属性名转为小写
atts=array_change_key_case((array)atts,CASE_LOWER);
//设置默认的属性键值对,且名字出现在数组的键部分的属性,才是被支持的属性。
//也就是,下面的数组定义了哪些属性被支持、默认值是多少。
default_atts=array(
color=yellow
);
atts=shortcode_atts(default_atts,atts,tag);
//业务逻辑代码,也就是你的短代码要做什么
returncontent;
}
functionshortcode_register()
{
add_shortcode(wporg,shortcode_handler);
}
add_action(init,shortcode_register);
4.2、定义单标签
?php
functionshortcode_handler(atts=array(),content=null,tag=)
{
//如果你的短代码支持属性,需要以下代码,将属性名转为小写
atts=array_change_key_case((array)atts,CASE_LOWER);
//设置默认的属性键值对,且名字出现在数组的键部分的属性,才是被支持的属性。
//也就是,下面的数组定义了哪些属性被支持、默认值是多少。
default_atts=array(
color=
);
atts=shortcode_atts(default_atts,atts,tag);
//业务逻辑代码,也就是你的短代码要做什么
//与双标签的区别是,content参数值永远是null,因为单标签无法包含内容
returncontent;
}
functionshortcode_register()
{
add_shortcode(wporg,shortcode_handler);
}
add_action(init,shortcode_register);
4.3、删除指定标签
/**
*移除[background]标签
*/
functionbackground_shortcode_remover()
{
remove_shortcode(background);
}
add_action(init,background_shortcode_remover,20);//优先级要小于11
五、原理分析
#1:在插件或主题中,注册短代码标签。
#2:在后台发布文章或页面时,在正文中添加短代码标签。
#3:在single.php或page.php中,调用the_content()函数,用于显示正文。
#4:当用户访问一个含有短代码标签的文章时,wordpress则会调用the_content()函数。
#5:the_content()函数,会执行挂载在the_content这个钩子下的所有函数,而do_shortcode()这个函数也挂载在此钩子下。
#6:执行do_shortcode()函数,匹配所有短代码标签并调用标签定义时指定的函数。