wordpress精简代码(WordPress短代码Shortcode的使用教程)WordPress / WordPress短代码使用教程...

wufei123 发布于 2024-04-27 阅读(49)

wordpress短代码的作用是,把它放到文章或者页面时,它会被替换成一些其它的内容wordpress短代码的使用非常简单,比如我们想显示最新的文章,可以使用短代码[recent-posts]或者设定一个参数来控制实现文章的数量。

[recent-posts posts="9"]或者给短代码增加一个标题[recent-posts posts=”9″]最新文章[/recent-posts]创建短代码的步奏1、创建一个函数,当wordpress发现短代码的时候会调用此函数

wordpress精简代码(WordPress短代码Shortcode的使用教程)WordPress / 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 = .get_the_title().;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的函数,它可以提取短代码的各个属性扩展一下我们之前的函数,传递一个参数$attsfunction recent_posts_function($atts)。

{extract(shortcode_atts(array(posts => 1,), $atts));query_posts(array(orderby => date, order => DESC , showposts => $posts));

if (have_posts()) :while (have_posts()) : the_post();$return_string = .get_the_title().;

endwhile;endif;wp_reset_query();return $return_string;}如果短代码中不传递参数,posts=>1 将是默认值,传递完参数将用参数的值,注意一下,短代码可以添加多个参数

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

{extract(shortcode_atts(array(posts => 1,), $atts));$return_string =

.$content.

;query_posts(array(orderby => date, order => DESC , showposts => $posts));

if (have_posts()) :while (have_posts()) : the_post();$return_string .= .get_the_title().;

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

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

宝骏汽车 新闻98261