其实完成短代码很简略,咱们只要要用到 WordPress 外面的一个函数就能够搞定短代码,外加本人的一个小函数,能够让短代码完成的轻松加欢快。
短代码完成原理
就像往 WP 一些举措里加钩子和过滤函数一样,
短代码只是通过封装了的针对文章输入内容的过滤器而已,
没有像有一些主题性能说的那么震撼、那么浅近。
上面来一个简略例子:
function myName() {//短代码要解决的函数
return "My name's XiangZi !";
}
//挂载短代码
//xz为短代码称号
//即你在编辑文章时输出[xz]就会执行 myName 函数
add_shortcode('xz', 'myName');
那么咱们在文章中输出[xz]就会失去
My name's XiangZi !
短代码传参
更浅近一点的利用,我将会在前面的文章中讲到,
明天只讲一下,短代码的传参机制
初级一点的例子
function myName($array,$content) {
var_dump($array);
var_dump($content);
}
add_shortcode('xz', 'myName');
编辑文章时咱们输出:
[xz a="1" b="2" c="3"]这里是三个参数哦[/xz]
在函数中咱们将失去:
//$array 是一个数组,
//大体构造如下
$array = array('a'=>'1','b'=>'2','c'=>'3');
//$content 是一个字符串
$content = '这里是三个参数哦';
shortcode_atts
不是由于搞短代码插件,我也不会用到这个函数,
shortcode_atts 函数次要是用来设置短代码中截获变量的初始值。
这是一个很适用的函数,其实这个函数的真正是作用在数组上得,
由于咱们从短代码中截获的参数都是数组方式的。
shortcode_atts 函数详解
不要被函数名所纳闷,在 WordPress 里次要是用于设置短代码参数的默许值,
假如咱们将代码提取进去,用在别的中央,该函数能够帮咱们设置一个既得数组的默许值。
shortcode_atts 函数应用
这个函数应用起来很简略。
shortcode_atts(array( "url" => 'http://PangBu.Com' ), $url)
以上代码的意思是,
将 $url 数组 键值为url的成员默许值设定为'http://PangBu.Com',
别的中央用途仿佛不多,但关于一些超级懒人,有时分揽到总是遗记或是懒得设定数组的数值时,这个函数超好用。
shortcode_atts 函数申明
/**
* Combine user attributes with known attributes and fill in defaults when needed.
*
* The pairs should be considered to be all of the attributes which are
* supported by the caller and given as a list. The returned attributes will
* only contain the attributes in the $pairs list.
*
* If the $atts list has unsupported attributes, then they will be ignored and
* removed from the final returned list.
*
* @since 2.5
*
* @param array $pairs Entire list of supported attributes and their defaults.
* @param array $atts User defined attributes in shortcode tag.
* @return array Combined and filtered attribute list.
*/
function shortcode_atts($pairs, $atts) {
$atts = (array)$atts;
$out = array();
foreach($pairs as $name => $default) {
if ( array_key_exists($name, $atts) )
$out[$name] = $atts[$name];
else
$out[$name] = $default;
}
return $out;
}
以上就是安达网络工作室关于《WordPress开发中短代码的实现及相关函数使用技巧》的一些看法。更多内容请查看本栏目更多内容!
渣滓评论曾经不是一个新颖的货色了,置信只需是日独立IP超越2000的网站,只需开放评论的话,每天都会收到几...
查问字符串指的是链接中后边的问号后的查问语句,格局为 key=value,多个查问语句用 & 符号离开。add_query...
要害字形容:博客 撰写 应用 如何 文章 能够 Wordpress 性能 这里 在上一次教程中引见了 Wordpress 的后盾...
为什么要静态加载文章? 1. 疾速向访客展现页面 文章很容是蕴含大量文字和多媒体资源 (如: 图片, 视频, ...
single_cat_title()函数 single_cat_title()函数,日常中咱们很少会用到,但这个函数会给咱们处理很多成绩,...
WordPress主题教程之修正wordpress回复评论文字办法,首选需求建设个自定义的评论模板,而后经过调用此...