2020-11-01 / 2994阅
WordPress的短代码是非常方便灵活的,和Discuz里面的代码编辑一样,你可以自己定义子短代码。今天我们先说说如何注册自己的短代码
function hello() { return 'Hello, World!'; } function hello_init() { add_shortcode('hw', 'hello'); } add_action('init','hello_init');
通过上面的代码,我们就成功注册了一个段代码。在编辑器中输入
[hello][/hello] 就可以使用了
当然,这样的段代码是固定内容的,可以用作一些不经常改变的固定内容,如果WordPress只能这样使用短代码,那就没有意思了,我们接着看
function hello($atts, $content=null, $code="") { // 这里content参数便是你要写的文字。 $return = '<div class="hello_short">'; $return .= $content; $return .= '</div>'; return $return; } add_shortcode('hw', 'hello');
上面的代码注册的短代码是可以传递参数的。
[hello]我是秦自龙[/hello]
上面的代码会输出
<div class="hello_short"> 我是秦自龙 </div>
function youran_shortcode($atts = [], $content = null, $tag = '') { // 格式化属性键,全部设置为小写 $atts = array_change_key_case((array)$atts, CASE_LOWER); // 用用户输入的属性覆盖默认属性 $youran_atts = shortcode_atts([ 'title' => '悠然自学网', ], $atts, $tag); // 开始输出内容 $html = '<div class="youran_box">'; $html .= '<h2>' . esc_html__($youran_atts['title'], 'youran') . '</h2>'; if (!is_null($content)) { // 过滤输出用户的传入的内容 $html .= apply_filters('the_content', $content); } $html .= '</div>'; return $html; } function youran_shortcodes_init() { add_shortcode('youran', 'youran_shortcode'); } add_action('init', 'youran_shortcodes_init');
$atts是用户传递的参数数组,$content是用户输入的内容,$tags是短代码的名称(就当他不存在)
阅读文章或者观看视频过程中有任何问题,请下方留言或者联系我Q248758228