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; }
如上代码,我们创建了一个回调函数,获取最新文章,并返回一个带链接的字符串,注意回调函数不打印任何内容,而是返回一个字符串。
function register_shortcodes(){ add_shortcode('recent-posts','recent_posts_function'); }
当文章中发现短代码[recent-posts]时,将会自动调用recent_posts_function()函数
add_action( 'init','register_shortcodes');
进阶短代码
1、短代码的参数
短代码非常灵活,它允许我们添加参数,假如我们要显示一定数量的最新文章,我们可以这样写
[recent-posts posts="9"]
但是如何在自定义函数中获取到短代码的参数呢?这里我们要用到两个函数shortcode_atts()函数和extract函数
shortcode_atts 作用是把用户短代码的属性和本地属性相结合
extract 此为PHP的函数,它可以提取短代码的各个属性。
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 将是默认值,传递完参数将用参数的值,注意一下,短代码可以添加多个参数
进一步扩展我们的短代码函数,添加一些内容作为参数传递,这将是最新文章列表的标题。为了实现这种功能,我们需要在函数中添加第二个参数$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]
在其它地方显示短代码
默认情况下侧边栏是忽略短代码的,想要实现需要添加对应的过滤函数
add_filter('widget_text','do_shortcode');
add_filter('comment_text','do_shortcode');
add_filter('the_excerpt','do_shortcode');
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。