Подсчитайте, сколько раз шорткод WordPress используется в публикации


У меня есть следующая функция шорткода 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]

В любом случае, чтобы изменить это?

Author: brasofilo, 2014-12-16

4 answers

Итак, изучив немного больше идеи @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++ .']';
}
 2
Author: CiprianD, 2014-12-18 14:29:25

Хороший вопрос. Возможное решение ниже, однако не совсем элегантное, потому что оно требует, чтобы у вас было фиксированное количество коротких кодов на каждой странице, например, 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;
}
 1
Author: diggy, 2014-12-16 15:10:15

Это происходит потому, что при каждой загрузке страницы вы переопределяете свою функцию, поэтому static $i=1; будет выполняться всегда.

Возможно, вы хотите использовать переменную $_SESSION. Но не забывайте о session_start() где-то в init обратном вызове.

function wp_shortcode() {
    if (empty($_SESSION["myCounter"])) {
        $_SESSION["myCounter"] = 1;
    }
    $return = '<a href="#f' . $_SESSION["myCounter"] . '" name="r' 
        . $_SESSION["myCounter"] . '">[' 
        . $_SESSION["myCounter"] . ']</a>';
    $_SESSION["myCounter"]++;
    return $return;
}
add_shortcode('shortcode', 'wp_shortcode');

Установив сеанс, поместите его в functions.php

add_action('init', 'my_init');
function my_init() {
    if (!session_id()) {
        session_start();
    }
    //Other init here
}
 0
Author: vaso123, 2014-12-16 15:03:20

Если вам нужно просто подсчитать общее количество тегов на странице/публикации, вы можете использовать это:

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;
}
 0
Author: nigelheap, 2018-02-26 18:06:05