WP 2.5 Shortcode 应用

WordPress 发布有一段时间了,由于最近学习忙,一直没时间仔细研究。
最近看 WordPress 官方文档的时候,发现 WordPress2.5 已经支持自定义 ShortCode了。

所谓 ShortCode ,就是类似于论坛的UBB代码一样,可以尽可能地减少xHTML代码数量。
详细内容及正确解释详见官方文档 -> http://codex.wordpress.org/Shortcode_API
WordPress2.5 内置了如下几个代码:

[footag] [bartag] [baztag]

我们也可以像 ActionScript 的自定义类 那样来自定义 ShortCode。 玩转了 ShortCode 的话,很多的辅助插件都可以下岗啦。

ShortCode基本语法:

function shortcode_handle( $atts, $content = null )
{
	// Do something you want here
}
add_shortcode ('myshortcode' , 'shortcode_handle' );

调用时,[myshortcode $atts = ... ] $content [/myshortcode]
PHP代码插入主题的 function.php 当中,后台撰写文章的时候即可直接调用。

PHP我玩的不熟,不知道写的意思大家能否明白。如果有错误还请大家多多指出改正。

下面俺自己试着写了两个ShortCode来玩玩。

第一个,插入Flash:
本来是用插件来实现的。但现在看来,ShortCode完全可以将其取代了。

function flash_function( $atts, $content = null )
{
	extract( shortcode_atts( array('width' => '400' , 'height' => '300'), $atts ) );
	return '<object width=" . $width . " height=" . $height . " data="' . $content . '" type="application/x-shockwave-flash"><param name="src" value="' . $content . '" /><param name="menu" value="false" /></object>' ;
}

调用: [ flash width=xx height=xx] FLASH URL [/ flash]

第二个,插入Mp3播放器:
Flash成功后,很容易就可以用一般的FlashPlayer来当作Flash音乐播放器了。我们只需要用FlashVars吧变量传递给SWF文件即可。

function audio_function ( $atts , $content = null )
{
	extract( array() , $atts ) ;
	return '<object width="290" height="24" data="http://blog.francistm.com/wp-includes/images/audio_player.swf" type="application/x-shockwave-flash"><param name="src" value="http://blog.francistm.com/wp-includes/images/audio_player.swf" /><param name="menu" value="false" /><param name="FlashVars" value="' . $content .'" /><param name="flashvars" value="' . $content .'" /></object>' ;
}

调用: [ sound] MUSIC URL [/ sound]
最后不要忘记替换掉 Flash Audio Player 的地址,然后用 add_shortcode 注册。

function.php 编辑时有危险,如果出现错误,只能手动进入FTP或其他方法修改,而无法访问整个Wordpress。

这样基本就可以替换掉两个插件了。
希望大家可以用这个方法做出更方便的功能。

Related Post

4 Responses to “WP 2.5 Shortcode 应用”


Leave a Reply

Your comment may be deleted in anytime.
Just keep comment area clean and tidy if you don't like.