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编程
版权声明:本文为 安达网络工作室 转载文章,如有侵权请联系我们及时删除。
相关文章
the_time WordPress日期和工夫调用函数

复制代码代码如下: <?php the_time('Y-m-d'); ?> 显示的是 2011-10-1 这样的,修正()中内容用以下字符交换...

wordpress获取文章评论数过滤掉作者代码分享

复制代码代码如下://获取文章评论数,不蕴含作者本人function get_comments_number_filter_author() { g...

菜鸟应用wordpress建站的几点心得

要害字形容:心得 建站 应用 菜鸟 能够 这个 边栏 主题 文章 一个   这一周都在学用wordpress来做独立博...

编写PHP脚原本完成WordPress中评论分页的性能

办法阐明 首先来看看可能被用到的办法. 关上文件 wp-includes/link-template.php 你会发现 WordPress 2.7 多...

修正PHP脚本使WordPress阻拦渣滓评论的办法示例

阻拦英文渣滓评论 因为绝大少数的渣滓评论都是英文的,所以国际不少冤家在应用 Some Chinese Please 插件,...

以WordPress为例解说jQuery丑化页面Title的办法

这里选取的例子,便是 WordPress 中比拟有名的丑化超链接Title成果,普通的 title 成果是把鼠标放到 a 元素...

需求提交

客服服务