WPLOGO

wordpress的短代码自定义—专属自己的UBB代码

记得在论坛火爆的时候,UBB是大家再熟悉不过的了,在没有“所见即所得”编辑器诞生之前,各种论坛里都充斥着UBB代码的时候例子,最典型的就是,当注册了一个论坛,在等级不够的时候不能在签名里使用UBB代码,这时候大家就想尽了各种办法想在签名里加图片,我就是那个时候才知道原来网站是用一个交HTML的语言编写的,HTML语言能形成各种样子。虽然现在随着可视化编辑器的成熟,UBB代码已经不再被大家熟知,但如果想用WORDPRESS进行比较大的CMS网站建设的朋友们,定制个UBB代码也是可以另外收费的嘛……(咳咳,貌似偏了),言归正传,开始干活!

官方给出的短代码(Shortcode)解释

Shortcode

Since Version 2.5 WordPress support so called Shortcodes. They have been introduced for creating macros to be use in a posts content. For examples of shortcodes and how to use them, see WordPress.com Shortcodes, though some shortcodes featured are exclusive to WordPress.com.

A trivial shortcode for a gallery looks like this:


You can also print a shortcode directly in a template like so:

<!--?php echo do_shortcode('

'); ?>

Shortcodes can be with additional attributes as the following example shows:


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.

上面文字说的基本上就是WordPress 2.5版本开始支持短代码(shortcode)……我英语不好,不丢人了。

下面就让我们一步步实现咱们的UBB代码。

一、简单的UBB代码
1.打开你主题文件夹里的functions.php文件,如果还没有,就建立一个,注意,是PHP,不是HTML哈。
2.将下面的代码复制进去。

function UBB_url($atts, $content = null) {//$atts和$content是必须包含的2个属性
extract(shortcode_atts(array("href" => 'href'), $atts));//创建一个属性,当然,也可以不定义属性
return ''.$content.'';
}
add_shortcode("url", "UBB_url");//前面的url是要定义的UBB名字,后面的是上面的函数

3.在文章中使用:

[url href="https://www.uazoh.com"]赵和邹设计工作室[/url]

最后的效果就是咱们熟悉的赵和邹设计工作室

二、进一步应用,加载指定分类文章列表

这个不同于插件,这个是完全代码实现的,并且是在发布文章时候可以自定义的,而且不一定是相关文章和最新文章。

1.复制到functions.php文件

function post_list($atts, $content = null) {
extract(shortcode_atts(array(
"num" => '5',//数量,默认值,建议定义一个
"cat" => ''//分类名,默认值,也可以定义一个,留空也可以
), $atts));
global $post;
$listposts = get_posts('numberposts='.$num.'&order=DESC&orderby=post_date&category='.$cat);
$retour='
      ';
 
      foreach($listposts as $post) :
 
      setup_postdata($post);
  '; endforeach; $retour.=' '; return $retour; } add_shortcode("list", "post_list");

2.在编辑文章的时候使用:

[list num="9" cat="11"]

最后效果就是调用了ID=11分类下的9篇文章。

有一点需要注意,就是UBB代码既然是在可视化编辑器之前的产物,那么就不要在可视化编辑器内使用,也就是要在WORDPRESS文本编辑器里使用哦~

发布者

优佐

Uazoh优佐生活