有时候想方便一些固定不变的内容的输入,我们可以借助 WordPress Shortcode 这个 API 来实现,这个 Shortcode 可以帮助我们非常方便的输入一些经常出现在不同博文但是内容不怎么需要变化的文章段落。下面老王就详细介绍下 WordPress Shortcode API 的用法。
一、最基本 Shortcode
在 functions.php 中加入以下代码:
function laowangblog_shortcode() {
return '<p>这个是老王博客,地址:<a href="https://laowangblog.com">老王博客</a></p>';
}
add_shortcode('laowangblog', 'laowangblog_shortcode');
之后在文章中直接输入 [laowangblog],就会返回那段设定好的代码:
<p>这个是老王博客,地址:<a href="https://laowangblog.com">老王博客</a></p>
二、带 content 的 Shortcode
有时候我们需要一些自定义的内容,可以通过 Shortcode 的 content 来实现。
在 functions.php 中加入以下代码:
function laowangblog_shortcode( $atts, $content = null ) {
return '<p>这个是老王博客,地址:<a href="https://laowangblog.com">老王博客</a>,今天天气:' . $content . '。</p>';
}
add_shortcode('laowangblog', 'laowangblog_shortcode');
之后在文章中直接输入 [laowangblog]晴[/laowangblog],就会返回那段设定好的代码:
<p>这个是老王博客,地址:<a href="https://laowangblog.com">老王博客</a>,今天天气:晴。</p>
三、带 atts 的 Shortcode
除了 content 可以自定义内容外,atts 也可以传递 Shortcode 的属性。
在 functions.php 中加入以下代码:
function caption_shortcode( $atts, $content = null ) {
$a = shortcode_atts( array(
'class' => 'caption',
), $atts );
return '<span class="' . esc_attr($a['class']) . '">' . $content . '</span>';
}
add_shortcode('caption', 'caption_shortcode');
之后在文章中直接输入:
就可以得到:
<span class="headline">My Caption</span>







