WordPress打造你自己的短代码

首先要了解什么是短代码。

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
2
3

function hello() {
    return 'Hello, World!';
}

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>

     这样的效果了。


转载于:https://my.oschina.net/ajian2014/blog/309125

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值