致力于为用户提供真实的
主机测评数据及优惠信息

WordPress中的shortcode短代码功能使用详解

WordPress 从 2.5 的版本开始,增加了一个 shortcode (短代码) API ,类似于 BBS 上的 BBCode , shortcode 也可以很方便的为文章或页面增加功能,并且 shortcode 的比起 BBCode 更加灵活和强大。下面 Kayo 为大家介绍一下 shortcode 。

一.shortcode 简介
shortcode 可以让开发者通过以函数的形式创建宏内容来生成内容,或许这个概念看上去有点模糊,但实际上它是一个很简单而实用的功能,只要会编写基本的 PHP 函数,即可使用 shortcode ,下文会以实际的例子来说明 shortcode 的使用方法。

二.shortcode 形式
shortcode 支持封闭标签和自闭(自动封闭)标签,并且支持在标签内使用参数,至于 shortcode 具体是何种形式,这就决定于开发者怎样编写这个 shortcode 了。

?
1
2
3
4
5
[myshortcode]Some Content[/myshortcode] // 封闭标签
[myshortcode] // 自闭标签
[myshortcode id="codetool">

三.shortcode 例子
在使用 shortcode 前,首先必须在主题的 functions.php 文件中定义 shortcode ,例如:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function myshortcode_function($atts, $content = null){ // $atts 代表了 shortcode 的各个参数,$content 为标签内的内容
 
 extract(shortcode_atts(array( // 使用 extract 函数解析标签内的参数
 "title" => '标题' // 给参数赋默认值,下面直接调用 $ 加上参数名输出参数值
 ), $atts));
 // 返回内容
 return '<div class="myshortcode">
    <h3>'. $title .'</h3>
    <p>
     '. $content .'
    </p>
   </div>';
}
 
add_shortcode("msc", "myshortcode_function"); // 注册该 shortcode,以后使用 [msc] 标签调用该 shortcode

把上面的代码添加到 functions.php 中,一个简单的 shortcode 便创建好了,我们可以通过 [msc][/msc]标签调用该 shortcode ,如:

?
1
[msc id="codetool">

在文章或页面内容中输入上面的调用,可以在相应的位置输出一段欢迎语句,在 style.css 中定义相应的 CSS ,即可为短代码赋予样式。

Kayo 简略的介绍了 WordPress 的短代码(shortcode) 功能,主要是介绍了 shortcode 的主要概念和使用方法。在本文中, Kayo 将会更加详细的介绍一下 shortcode 中较为重要的 API ,希望有助于各位开发较为复杂的 shortcode 。

四.函数 add_shortcode

该函数用于注册一个 shortcode ,它有两个参数:短代码名与 shortcode 处理函数名,引用上文的例子:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function myshortcode_function($atts, $content = null){ // $atts 代表了 shortcode 的各个参数,$content 为标签内的内容
 
 extract(shortcode_atts(array( // 使用 extract 函数解析标签内的参数
 "title" => '标题' // 给参数赋默认值,下面直接调用 $ 加上参数名输出参数值
 ), $atts));
 // 返回内容
 return '<div class="myshortcode">
    <h3>'. $title .'</h3>
    <p>
     '. $content .'
    </p>
   </div>';
}
 
add_shortcode("msc", "myshortcode_function"); // 注册该 shortcode,以后使用 [msc] 标签调用该 shortcode

msc 即为短代码名,以后在写文章或页面时可以直接使用 [msc][/msc] 标签调用该短代码,而 "myshortcode_function" 即为例子中的短代码处理函数的名称。下面重点分析短代码处理函数。

五.短代码处理函数

shortcode 处理函数是一个 shortcode 的核心, shortcode 处理函数类似于 Flickr(WordPress 过滤器),它们都接受特定参数,并返回一定的结果。 shortcode 处理器接受两个参数, $attr 和 $content , $attr 代表 shortcode 的各个属性参数,从本质上来说是一个关联数组,而 $content 代表 shortcode 标签中的内容。

如上面的例子,若在文章内作出调用,输出一段欢迎语句:

[msc php" id="highlighter_111994">

?
1
array( 'title' => '欢迎')

赞(0) 打赏
未经允许不得转载:爱主机 » WordPress中的shortcode短代码功能使用详解
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

© 2019-2024   爱主机   网站地图

  • 陕ICP备2021013503号-2
  • 请求次数:46 次,加载用时:0.233 秒,内存占用:8.21 MB