WordPress开发中短代码的完成及相干函数应用技巧

其实完成短代码很简略,咱们只要要用到 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 短代码 PHP PHP编程
版权声明:本文为 安达网络工作室 转载文章,如有侵权请联系我们及时删除。
相关文章
WordPress主题制造之模板文件的引入办法

get_template_part() 用来援用模板文件,相似于 get_header()、get_sidebar() 和 get_footer(),只不过这个...

Wordpress完成文章支持和拥护性能的办法

本文实例讲述了Wordpress完成文章支持和拥护性能的办法。分享给大家供大家参考。详细剖析如下: 假如你上网...

wordpress非插件完成增加链接转跳性能

链接方式http://localhost/?go=http://www.baidu.com这种方式转跳的办法。 复制代码代码如下:add_action('w...

wordpress在lighttpd下的重写规定及留意细节

wordpress博客是应用人数最多的一个开源博客顺序,动态化也是最多人像要到的成绩,关于老手来收,动态化的解...

简略理解将WordPress中的工具栏移到底部的小技巧

从 WordPress 3.1 开端引入了工具栏的概念,当用户登录后在前台和后盾的页面顶部会显示一个黑色的工具栏,经...

wordpress 网站转移效劳器操作的两种办法

第一种办法:我的这个博客不断都在网上运转,明天想把它在本地架设一个,包括数据库都和网上的如出一辙。详...

需求提交

客服服务