微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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');

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐