首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >统计文章中使用WordPress短代码的次数

问统计文章中使用WordPress短代码的次数
EN

Stack Overflow用户
提问于 2014-12-16 14:49:39
回答 4查看 3.9K关注 0票数 4

我有以下WordPress短代码函数:

代码语言:javascript
复制
function wp_shortcode() {
 static $i=1;
 $return = '['.$i.']';
 $i++;
 return $return;
}
add_shortcode('shortcode', 'wp_shortcode');

这个很好用。在本文中每次调用函数时,$i变量都会增加。所以为了

代码语言:javascript
复制
[shortcode][shortcode][shortcode][shortcode]

输出如预期的那样

代码语言:javascript
复制
[1][2][3][4]

但

如果文章有多页,则在下一篇文章页上重新设置计数器。因此:

代码语言:javascript
复制
[shortcode][shortcode][shortcode][shortcode]
<!--nextpage-->
[shortcode][shortcode][shortcode][shortcode]

输出是

代码语言:javascript
复制
[1][2][3][4]
<!--nextpage-->
[1][2][3][4]

而不是想要的输出:

代码语言:javascript
复制
[1][2][3][4]
<!--nextpage-->
[5][6][7][8]

要改变这个吗?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2014-12-18 13:06:03

因此,在对@diggy的想法进行了更多的研究之后,在对the_content进行预处理并在呈现短代码之前将$atts添加到短代码中后,我想出了如下结论:

代码语言:javascript
复制
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++ .']';
}
票数 2
EN

Stack Overflow用户

发布于 2014-12-16 15:10:15

问得好。下面是一个可能的解决方案,但并不是很优雅,因为它要求您在每一页上都有固定数量的短代码,例如4:

代码语言:javascript
复制
add_shortcode( 'shortcode', 'wp_shortcode' );
function wp_shortcode() {
    global $page;
    $spp = 4;
    static $i = 1;
    $ii = $i + ( ( $page - 1 ) * $spp );
    $return = '<a href="#f'.$ii.'" name="r'.$ii.'">['.$ii.']</a>';
    $i++;
    return $return;
}
票数 1
EN

Stack Overflow用户

发布于 2018-02-26 18:06:05

如果只需要计算页面/帖子中的总标记,可以使用以下方法:

代码语言:javascript
复制
function count_shortcodes( $content, $tag ) {
    if ( false === strpos( $content, '[' ) ) {
        return 0;
    }

    if ( shortcode_exists( $tag ) ) {
        preg_match_all( '/' . get_shortcode_regex() . '/', $content, $matches, PREG_SET_ORDER );
        if ( empty( $matches ) )
            return 0;

        $count = 0;
        foreach ( $matches as $shortcode ) {
            if ( $tag === $shortcode[2] ) {
                $count++;
            } elseif ( ! empty( $shortcode[5] ) && has_shortcode( $shortcode[5], $tag ) ) {
                $count++;
            }
        }

        return $count;
    }
    return 0;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27507320

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档