WordPress短代码Shortcode的使用教程

wordpress短代码的作用是,把它放到文章或者页面时,它会被替换成一些其它的内容。

wordpress短代码的使用非常简单,比如我们想显示最新的文章,可以使用短代码

[recent-posts]

或者设定一个参数来控制实现文章的数量

[recent-posts posts="9"]

或者给短代码增加一个标题
[recent-posts posts=”9″]最新文章[/recent-posts]

创建短代码的步奏

1、创建一个函数,当wordpress发现短代码的时候会调用此函数
2、设置唯一的名称,来注册短代码
3、把注册的函数绑定到wordpress的action上

实例说明

1、创建回调函数

当wordpress发现短代码时,会用这段函数的代码进行替换

function recent_posts_function()
{
query_posts(array('orderby' => 'date','order' => 'DESC','showposts' => 1));
if (have_posts()) :
while (have_posts()) : the_post();
$return_string = '<a href="'.get_permalink().'">'.get_the_title().'</a>';
endwhile;
endif;
wp_reset_query();
return $return_string;
}

如上代码,我们创建了一个回调函数,获取最新文章,并返回一个带链接的字符串,注意回调函数不打印任何内容,而是返回一个字符串。

2、注册短代码

现在我们注册一个短代码,以便wordpress可以识别

function register_shortcodes(){
add_shortcode('recent-posts','recent_posts_function');
}

当文章中发现短代码[recent-posts]时,将会自动调用recent_posts_function()函数

3、将短代码绑定到wordpress的钩子上

add_action( 'init','register_shortcodes');

现在可以创建一篇文章将短代码加人到文章中看看是否好用吧。

进阶短代码

1、短代码的参数

短代码非常灵活,它允许我们添加参数,假如我们要显示一定数量的最新文章,我们可以这样写

[recent-posts posts="9"]

但是如何在自定义函数中获取到短代码的参数呢?这里我们要用到两个函数shortcode_atts()函数和extract函数

shortcode_atts 作用是把用户短代码的属性和本地属性相结合
extract 此为PHP的函数,它可以提取短代码的各个属性。

扩展一下我们之前的函数,传递一个参数$atts

function recent_posts_function($atts)
{
extract(shortcode_atts(array(
'posts' => 1,),$atts));
query_posts(array('orderby' => 'date','showposts' => $posts));
if (have_posts()) :
while (have_posts()) : the_post();
$return_string = '<a href="'.get_permalink().'">'.get_the_title().'</a>';
endwhile;
endif;
wp_reset_query();
return $return_string;
}

如果短代码中不传递参数,posts=>1 将是默认值,传递完参数将用参数的值,注意一下,短代码可以添加多个参数

2、短代码中添加内容

进一步扩展我们的短代码函数,添加一些内容作为参数传递,这将是最新文章列表的标题。为了实现这种功能,我们需要在函数中添加第二个参数$content。

function recent_posts_function($atts,$content=null)
{
extract(shortcode_atts(array(
'posts' => 1,$atts));
$return_string = '<h3>'.$content.'</h3>';
query_posts(array('orderby' => 'date','showposts' => $posts));
if (have_posts()) :
while (have_posts()) : the_post();
$return_string .= '<a href="'.get_permalink().'">'.get_the_title().'</a>';
endwhile;
endif;
wp_reset_query();
return $return_string;
}

上面的回调函数,短代码使用与[recent–posts posts=”5″]最新文章[/recent–posts]

在其它地方显示短代码

默认情况下侧边栏是忽略短代码的,想要实现需要添加对应的过滤函数

1、在侧边栏显示

add_filter('widget_text','do_shortcode');

2、在评论页面显示

add_filter('comment_text','do_shortcode');

3、在摘要中显示

add_filter('the_excerpt','do_shortcode');

相关文章

我想将wordpress的默认接口路由改掉,愿意是默认的带一个 wp...
wordpress自定义分类法之后,我看到链接都自动在后面添加了一...
事情是这样的,我用 get_post_type 函数创建了一个自定义分类...
最近网站莫名其妙的被顶上了,过一个多小时,就注册一个账号...
最近服务器要到期了,就想着把网站转移到另外一台服务器,本...
今天在写wordpress的接口,然后碰到个奇怪的问题,怎么访问都...