WordPress Shortcode(简码)介绍及使用详解
WordPress 从 2.5 版本开始增加了一个类似 BBCode 标签的 Shortcode API,可以使用它在日志的内容中来给日志内容添加各种功能。Shortcode 这个接口非常容易使用,并且功能非常强大。
简单说 WordPress Shortcode 指的是一些使用[]包含的短代码,WordPress会识别这些短代码并根据短代码的定义输出为特定的内容。
Shortcode 类型
Shortcode API 支持几乎所有可能的组合形式:自关闭标签,开放标签,含有参数的标签等。
1 |
[mycode] |
Shortcode 基本概念
首先你要去定义一个函数,来处理你定义的 Shortcode,和它的属性参数以及引用的内容。
1 |
function my_shortcode_func($attr, $content) { |
然后把自己定义的 Shortcode 和其处理函数管理起来,以便 [mycode attr="value"]content[/mycode] 能够按照预期执行。
1 |
add_shortcode('mycode', 'my_shortcode_func') |
Shortcode 相关的所有函数
WordPress 定义了以下和 Shortcode 相关的函数:
1 |
add_shortcode('mycode', 'function_name'); // 定义一个新的 Shortcode |
一个简单的 Shortcode 例子
以我爱水煮鱼写的 Antispambot ShortCode 插件为例,内容就是邮箱地址,有个参数 $link
为 1 时候,把邮箱显示可点击,参数如下:
1 |
function antispambot_shortcode_handler($atts, $content='') { |
使用 Shortcode 投放 Google Adsense 广告
把下面的代码保存到你当前的主题的 functions.php
,或者上传到插件目录下并激活。
1 |
<?php |
然后你就可以通过撰写文章的时候,在相应的位置输入 [adsense]
你的 468×60 的广告代码(默认的广告代码),如果你想插入 300×250 的广告代码,在文章内容中插入 [adsense type="300x250"]
,当然你也可以扩展上面的代码增加更多广告的格式和类型。
这样就可以想把广告插在文章中的哪个位置,就能插在哪个位置了, 非常方便。
在侧边栏 Widgets 中使用 Shortcode
Shortcode 很方便,但是只能用在日志内容中,那么如何在 WordPress 的侧边栏的 Widgets 中使用 Shortcode,在当前主题的 functions.php
中添加如下代码:
1 |
add_filter('widget_text', 'do_shortcode'); |
然后你在 WordPress 后台 > 外观 > Widgets 界面添加一个文本 Widget,然后插入博客中经启用 shortcode 即可。
在主题的文件中使用 Shortcode
如果你想用在主题文件中使用名为 [my_shortcode] 的 Shortcode,你只需要按照下面的方式使用do_shortcode()
函数即可:
1 |
<?php echo do_shortcode("[my_shortcode]"); ?> |
解决 Shortcode 中自动添加的 br 或者 p 标签
我们在使用 WordPress Shortcode API 开发插件的时候,有个比较麻烦的问题,就是 WordPress 会自动在 shortcode 内添加 br 或者 p 标签,这样可能会打乱你的原先预想的 HTML 结构和布局。
造成这个问题的原因是 WordPress 默认的日志内容处理流程中,wpautop(将回车转换成 p 或者 br 标签的函数)是在 Shortcode 前面运行的。所以我们的解决方案也是非常简单,改变它们执行的顺序,在当前主题的 functions.php
文件中添加:
1 |
remove_filter( 'the_content', 'wpautop' ); |
这样调整顺序之后,你的 shortcode 里面的内容,就不会有自动添加的 p 或者 br 标签,但是如果 shortcode 中部分的内容你又需要一些 p 或者 br 标签用来换行的话,你需要自己手动在自己 shortcode 处理程序中添加 wpautop 来处理了。
1 |
function bio_shortcode($atts, $content = null) { |
转:
https://www.wpdaxue.com/wordpress-shortcode.html
最新文章
- 前端学PHP之数据类型
- Express调用mssql驱动公共类dbHelper
- SVN不能提交时的处理
- mod_wsgi
- Oracle ORA-01555 快照过旧 说明
- cuda编程学习5——波纹ripple
- E - 钱币兑换问题
- 用最简单的例子实现jQuery图片即时上传
- Scala:数组
- typeScript 学习
- 小程序蓝牙BLE——自动连接设备(手环)
- [LeetCode&;Python] Problem 744. Find Smallest Letter Greater Than Target
- #Leetcode# 788. Rotated Digits
- 【ASP.Net】publish asp.net to local IIS
- love is ... ...
- 20145311王亦徐《网络对抗技术》MAL_逆向与Bof基础
- kubernetes 1.9部署实践
- Python unittest模块心得(二)
- 几个简单if程序的细节比较与加法程序设计
- Attribute在.net编程中的应用(一)
热门文章
- jq的$.each遍历数组
- Tomcat启动web项目报Bad version number in .class file (unable to load class ...)错误的解决方法
- tinyxml源码解析(上)
- Divide by Three CodeForces - 792C
- mysql的IFNULL()函数FLOOR(),ROUND()函数
- POJ 3111 二分
- POJ2528 线段树离散化
- idea 创建多模块时模块类无法引入
- Android数据过滤器:Filter
- spring和Quartz的集群(二)