WordPress开发中短代码的实现及相关函数使用技巧

yipeiwu_com6年前PHP代码库

其实实现短代码很简单,我们只需要用到 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;
}

相关文章

PHP之uniqid()函数用法

本文实例讲述了PHP中uniqid()函数的用法。分享给大家供大家参考。具体方法分析如下: uniqid() 函数基于以微秒计的当前时间,生成一个唯一的 ID。 注释:由于基于系统时间,...

php中解析带中文字符的url函数分享

很多时候,在书写网页应用程序时候,会遇到中文和其他字符冲突的问题,例如有的url链接中包含中文字符,那么在使用wget/curl/file_get_contents等等获取信息时候会直接...

PHP使用xpath解析XML的方法详解

本文实例讲述了PHP使用xpath解析XML的方法。分享给大家供大家参考,具体如下: XML文件在PHP网站开发的轻量级应用中使用非常广泛,而PHP解析和读取XML文件的方式有很多种,比...

php Notice: Undefined index 错误提示解决方法

第一种方法:如果不影响程序的正常执行,可以采用屏蔽的方法可以在代码的第一行 加上 error_reporting(E_ALL ^ E_NOTICE); 关闭掉 NOTICE错误的警告第二...

php查看当前Session的ID实例

本文实例讲述了php查看当前Session的ID的方法。分享给大家供大家参考。具体如下: 有两种方法可以得到用户的session id,第一是使用session_id()函数,另外一种是...