其实完成短代码很简略,咱们只要要用到 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开发中短代码的实现及相关函数使用技巧》的一些看法。更多内容请查看本栏目更多内容!
本文实例讲述了WordPress如何完成用户主动登录性能的办法,其实就是很简略的让用户记住登录明码了,下次主动登...
自己2012年12月20日左右接触wordpress,至今曾经两个月。由于以前丝毫没有网站治理经历及编程才能,因而...
WordPress 3.5 新增加了一个提醒框性能,能够创立一个提醒框,而后指向任何元素,比方下边的例子: 本文就...
wordpress经过以后文章的ID获取文章的信息用的极多,在wordpress二次开发中,上篇文章说过,获取以后文章id...
导航菜单 导航菜单早已 "深化民意", 在博客上的使用日益重要且多样. 从本文开端, 我将展开几个对于 WordPre...
给一篇好的文章增加一些分享按钮分享到一些知名网站,很利于网站的推行。给站点增加分享按钮的办法很多,你...