首页 > 开发 > PHP > 正文

详解WordPress中简码格式标签编写的基本方法

2024-05-04 22:33:23
字体:
来源:转载
供稿:网友

WordPress 简码是一种类似于论坛标签的东西,格式类似于把尖括号换成中括号的 Html 标签。简码很多人叫做短代码,但官方的翻译应该是简码,在这里纠正一下。

简码的开发的逻辑比较简单,主要就是添加、删除和判断,会在本文全部介绍。

简码格式

简码的格式非常灵活,可以是有属性、无属性、闭合、非闭合等等:

[example]

[example]内容[/example]

[example attr="属性" attr-hide="1"]内容[/example]

[example "属性"]

添加简码

添加简码需要使用 add_shortcode() 函数,两个属性,第一个为简码名,第二个是简码的回调函数。

add_shortcode( $tag, $func );

例如添加名为 test 的简码,回调 Bing_shortcode_test() 函数:

function Bing_shortcode_test( $attr, $content ){  return 'Hello World!';}add_shortcode( 'test', 'Bing_shortcode_test' );

在文章中添加 [test] 就会输出 “Hello World!”。

从上边的例子可以看到,简码的回调函数需要接收两个参数。第一个是简码所有的属性,通过数组储存;第二个是简码的内容(闭合简码中的内容)。

移除简码

remove_shortcode() 函数可以移除一个简码,只需要指定简码的名称即可移除。

remove_shortcode( 'test' );

remove_all_shortcodes() 函数用来移除当前添加的所有简码。

remove_all_shortcodes();

判断简码

关于判断简码,有两个函数,shortcode_exists() 函数判断简码是否存在。

remove_all_shortcodes();if( shortcode_exists( 'test' ) ) echo '简码 test 存在';//Falseadd_shortcode( 'test', 'Bing_shortcode_test' );if( shortcode_exists( 'test' ) ) echo '简码 test 存在';//True

还有一个 has_shortcode() 函数,判断字符串中是否出现某某简码。

$content = '测试测试测试测试测试测试测试测试';if( has_shortcode( $content, 'test' ) ) echo '字符串中有 test 简码';//False$content = '测试测试测试测[test]测试[/test]试测试测试测试测试';if( has_shortcode( $content, 'test' ) ) echo '字符串中有 test 简码';//True

执行简码

do_shortcode() 函数用来在字符串中查找简码,并在简码处调用之前添加的回调函数,把简码执行成需要的内容。

WordPress 添加的钩子:

add_filter( 'the_content', 'do_shortcode', 11 );

例子:

function Bing_shortcode_test( $attr, $content ){  return 'Hello World!';}add_shortcode( 'test', 'Bing_shortcode_test' );$content = '测试测试测试测[test]试测试测试测试测试';echo do_shortcode( $content );//测试测试测试测Hello World!试测试测试测试测试

简码属性

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表