计算帖子中使用 WordPress 简码的次数 [英] Count the number of times a WordPress shortcode is used in a post

查看:26
本文介绍了计算帖子中使用 WordPress 简码的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 WordPress 短代码功能:

I have the following WordPress shortcode function:

function wp_shortcode() {
 static $i=1;
 $return = '['.$i.']';
 $i++;
 return $return;
}
add_shortcode('shortcode', 'wp_shortcode');

这很好用.每次在文章中调用函数时,$i 变量都会增加.所以对于

This works fine. The $i variable gets incremented each time the function is called in the article. So for

[shortcode][shortcode][shortcode][shortcode]

输出符合预期

[1][2][3][4]

但是

如果文章超过一页,则计数器会在下一篇文章页面上重置.所以对于:

if the article has more than one page, than the counter resets on the next article page. So for:

[shortcode][shortcode][shortcode][shortcode]
<!--nextpage-->
[shortcode][shortcode][shortcode][shortcode]

输出是

[1][2][3][4]
<!--nextpage-->
[1][2][3][4]

而不是想要的输出:

[1][2][3][4]
<!--nextpage-->
[5][6][7][8]

无论如何要改变这个?

推荐答案

因此,在对 @diggy 的想法进行了更多研究后,对 the_content 进行预处理并将 $atts 添加到短代码渲染之前,我想出了这个:

So after researching a bit more @diggy's idea with pre processing the_content and adding the $atts to the shorcodes before the shortcodes are rendered, I came up with this:

function my_shortcode_content( $content ) {
 //check to see if the post has your shortcode, skip do nothing if not found
 if( has_shortcode( $content, 'shortcode' ) ):

  //replace any shortcodes to the basic form ([shortcode 1] back to [shortcode])
  //usefull when the post is edited and more shortcodes are added
  $content = preg_replace('/shortcode .]/', 'shortcode]', $content);

  //loop the content and replace the basic shortcodes with the incremented value
  $content = preg_replace_callback('/shortocode]/', 'rep_count', $content);

 endif;

return $content;
}
add_filter( 'content_save_pre' , 'my_shortcode_content' , 10, 1);

function rep_count($matches) {
 static $i = 1;
return 'shortcode ' . $i++ .']';
}

这篇关于计算帖子中使用 WordPress 简码的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆