我有以下WordPress短代码函数:
function wp_shortcode() {
static $i=1;
$return = '['.$i.']';
$i++;
return $return;
}
add_shortcode('shortcode', 'wp_shortcode');这个很好用。在本文中每次调用函数时,$i变量都会增加。所以为了
[shortcode][shortcode][shortcode][shortcode]输出如预期的那样
[1][2][3][4]但
如果文章有多页,则在下一篇文章页上重新设置计数器。因此:
[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]要改变这个吗?
发布于 2014-12-18 13:06:03
因此,在对@diggy的想法进行了更多的研究之后,在对the_content进行预处理并在呈现短代码之前将$atts添加到短代码中后,我想出了如下结论:
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++ .']';
}发布于 2014-12-16 15:10:15
问得好。下面是一个可能的解决方案,但并不是很优雅,因为它要求您在每一页上都有固定数量的短代码,例如4:
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;
}发布于 2018-02-26 18:06:05
如果只需要计算页面/帖子中的总标记,可以使用以下方法:
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;
}https://stackoverflow.com/questions/27507320
复制相似问题