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]
此时在PHP函数内部将接收到解析后的数据:
//$array 是一个数组,
//大体结构如下
$array = array('a'=>'1','b'=>'2','c'=>'3');
//$content 是一个字符串
$content = '这里是三个参数哦';
shortcode_atts函数详解与应用
shortcode_atts函数主要用于为短代码中捕获的变量提供初始值。由于从短代码获取的参数通常以数组形式存在,该函数在处理数组方面具有实际效用。
尽管函数名看似复杂,但在WordPress环境中,其核心用途是设定短代码参数的默认值。若将此逻辑提取至其他场景,它也能帮助为既有数组填充默认配置。
该函数的使用方式十分直观简便。
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;
}