首先要了解什么是短代码。
Shortcode
Since Version 2.5 WordPress support so called Shortcodes. They have been introduced for creating macros to be use in a posts content.
A trivial shortcode for a gallery looks like this:
1 | [gallery] |
You can also print a shortcode directly in a template like so:
1 | <?php echo do_shortcode[gallery]; ?> |
Shortcodes can be with additional attributes as the following example shows:
1 | [gallery id="123" size="medium"] |
Both examples will display an image gallery which would be hard to maintain when writing the HTML markup for it and keeping it in sync with uploaded images."
怎么写一个自己的短代码呢?老师说从Hello World开始!
Follow Me
1.打开主题中的functions.php文件。如不存在此文件,创建一个。
2.定义hello()函数,返回字符串
1 | function hello() { |
3.使用add_shortcode()函数将你的hello()函数绑定为短代码,并命名为“hw”
1 | add_shortcode('hw', 'hello'); |
4.收工,测试。在你的文章中直接输入[hw]见证奇迹的出现。
当然,在实际写文章的时候你不会去弄个函数来输出个常量。比如我要实现上面的效果怎么办呢?首先你要一个图片效果。然后更改上面的函数:
function hello($atts, $content=null, $code="") {
// 这里content参数便是你要写的文字。
$return = '<div class="hello_short">';
$return .= $content;
$return .= '</div>';
return $return;
}
当然还有应该有相应的CSS
.hello_short{margin:20px 0px;padding: 15px 15px 15px 70px; font-size:12px;-moz-box-shadow:0px 1px 2px rgba(0, 0, 0, 0.1); -webkit-box-shadow:0px 1px 2px rgba(0, 0, 0, 0.1); box-shadow:0px 1px 2px rgba(0, 0, 0, 0.1);border-radius:5px;-webkit-border-radius:5px;-moz-border-radius:5px;-khtml-border-radius:5px;}
.hello_short a{}
.hello_short a:hover{}
.hello_short b,.hello_short strong{padding:0px; margin:0px; background: none; font-weight: bold;border-radius:0px;-moz-border-radius:0px;}
.hello_short{background: url(images/shortcode/warning.png) no-repeat 20px 20px #fff0b5;border: 1px solid #eac946;color: #b09e56;}
.hello_short a{ color:#A84A1E;}
现在你在文章中输入
[hello]我们的祖国是花园,花园里的花朵真鲜艳[/hello]
就能实现
<div style="background: url(http://mouse.orangemouse.me/wp-content/themes/mouser_final/images/shortcode/warning.png) no-repeat 20px 20px #FFF0B5;border: 1px solid #EAC946;color: #B09E56;margin: 20px 0px;padding: 15px 15px 15px 70px;font-size: 12px;">
我们的祖国是花园<br>
花园里的花朵真鲜艳
</div>
这样的效果了。