shortcode 在wordpress 中的使用方法的简单介绍

作者

shortcode 的意思是短代码的意思。 在wordpress中是通过短码可以生成一些自定义的内容。比如你想在文章的结尾插入当前页面打开的时间。虽然这个需求没什么用,不过可以说明一下wordpress 中 shortcode是怎么工作的。

下面这个示例,表示,如果你在当前的文章中写入了一个短码 [time] 那么如果输出内容的时候, [time]就会变成当前的时间。这一些是怎么完成的,操作的步骤是什么?

把一个短码[time]变成当前的时间

  1. 给短码起个名字,比如 time
  2. 使用的方法,在文章的结尾写上 [time]
  3. 创建一个关于 短码time 函数,用来生成内容
<?php
function my_short_time($attr, $content, $tags) {
    echo date("Y-m-d H:i:s") . "\n";
}

// 增加一个短码的钩子,用来处理 [time] / [time /] / [time][/time] 三种类型的短标签
add_shortcode('time', 'my_short_time');

// 执行短码钩子,可以直接查看输出
do_shortcode('[time]');
do_shortcode('[time /]');
do_shortcode('[time][/time]');

wordpress 一篇文章输出的时候怎么执行短代码

  1. 使用 the_content() 就是会自动调用。
  2. 使用 $post->post_content 进行测试
echo do_shortcode($post->post_content);

简单的说明

  1. add_shortcode 表示增加一个短码,一个参数是处理的短码是什么, 二是是处理短码的函数是什么
  2. do_shortcode 表示执行一个短码
  3. add_shortcode 中的二个参数,是一个函数。该函数有三个参数 1. 属性数组 2. 内容, 3. 当前的短码名

wordpress 短码 shortcode 中的属性和内容

首先看一个示例

function my_short_func($atts, $content, $tags) {

//    $atts = shortcode_atts(array(
//        "website" => "liuhaolin.com",
//    ), $atts);

    var_dump($atts);
    var_dump($content);
    var_dump($tags);
}


add_shortcode('my_short_code', 'my_short_func');
do_shortcode('[my_short_code attr1="one", attr2="two" ]xxxxx[/my_short_code]');

比如这个短码 [my_short_code attr1="one", attr2="two" ]xxxxx[/my_short_code]
属性有两个 attr1, attr2
短码的内容 xxxxx
当前短码的名字 my_short_code

输出的结果

array(2) {
  ["attr1"]=>
  string(3) "one"
  ["attr2"]=>
  string(3) "two"
}
string(5) "xxxxx"
string(13) "my_short_code"

一些相关的函数

Function: do_shortcode()
Function: add_shortcode()
Function: remove_shortcode()
Function: remove_all_shortcodes()
Function: shortcode_atts()
Function: strip_shortcodes()
Function: shortcode_exists()
Function: has_shortcode()
Function: get_shortcode_regex()
Function: wp_audio_shortcode()
Function: wp_video_shortcode()
Filter: no_texturize_shortcodes

回复

您的电子邮箱地址不会被公开。