Наша совместная команда Banwar.org

Связаться с нами

  • (097) ?601-88-87
    (067) ?493-44-27
    (096) ?830-00-01

Статьи

get_shortcode_regex () - Повертає регулярний вираз яке використовується для пошуку шоткодов в тексті. Функція WordPress.

  1. повертає
  2. Використання
  3. # 3. Перевіримо чи використовується в пості потрібний шоткод
  4. # 4. Перевірка наявності шоткода в тексті кількох постів
  5. нотатки
  6. cвязана функції

Повертає регулярний вираз яке використовується для пошуку шоткодов в тексті.

Ця функція об'єднує всі зареєстровані теги шоткодов в одне регулярний вираз.

✈ 1 раз = 0.000015с = дуже швидко | 50000 раз = 0.07с = швидкість світла | PHP 7.0.8, WP 4.6.1

Хуков немає.

повертає

Рядок. Регулярний вираз.

Використання

$ Pattern = get_shortcode_regex ($ tagnames); $ tagnames (масив) Список шорткодов, які потрібно знайти. З WP 4.4.
За замовчуванням: null (всі зареєстровані шорткоди)

приклади

# 1. Що повертає функція

echo get_shortcode_regex (); // виведе приблизно такий рядок, залежить від зареєстрованих шоткодов // \ [(\ [?) (Embed | wp_caption | caption | gallery | playlist | audio | video | code_snippet | democracy | democracy_archives | download) (?! [\ W- ]) ([^ \] \ /] * (?: \ / (?! \]) [^ \] \ /] *) *?) (?: (\ /) \] | \] (? :( [^ \ [] * + (?: \ [(?! \ / \ 2 \]) [^ \ [] * +) * +) \ [\ / \ 2 \])?) (\]?)

# 2 Вказуємо потрібних шоткод

Цей приклад показує, що поверне функція, що використання параметра $ tagnames.

echo get_shortcode_regex (array ( 'mytag')); //> \ [(\ [?) (Mytag) (?! [\ W -]) ([^ \] \ /] * (?: \ / (?! \]) [^ \] \ /] * ) *?) (?: (\ /) \] | \] (?: ([^ \ [] * + (?: \ [(?! \ / \ 2 \]) [^ \ [] * +) * +) \ [\ / \ 2 \])?) (\]?)

# 3. Перевіримо чи використовується в пості потрібний шоткод

Перевіримо наявність в текс шоткода your-shortcode і зробимо щось якщо використовується:

add_action ( 'wp', 'your_prefix_detect_shortcode'); function your_prefix_detect_shortcode () {global $ post; $ Pattern = get_shortcode_regex (); if (preg_match_all ( '/'. $ pattern. '/ s', $ post-> post_content, $ matches) && array_key_exists (2, $ matches) && in_array ( 'your-shortcode', $ matches [2])) { // Шоткод використовується}}

Цей приклад буде працювати, якщо глобальна змінна $ post визначена. wp - найраніше дію, коли ми може це визначити.

Для перевірки наявності шоткода, також є спеціальна функція has_shortcode ()

# 4. Перевірка наявності шоткода в тексті кількох постів

Цей приклад дуже схожий на попередній, з тією лише різницею, що він дозволяє перевірити всі пости на наявність в їх контенті потрібного нам шоткода videoannotation:

add_action ( 'wp', 'your_prefix_detect_shortcode'); function your_prefix_detect_shortcode () {global $ wp_query; $ Posts = $ wp_query-> posts; $ Pattern = get_shortcode_regex (); foreach ($ posts as $ post) {if (preg_match_all ( '/'. $ pattern. '/ s', $ post-> post_content, $ matches) && array_key_exists (2, $ matches) && in_array ( 'videoannotation', $ matches [2])) {// підключаємо свій сss і js break; // визначили що потрібно підключати стилі і гарний ...}}}

нотатки

  • Global. Масив. $ shortcode_tags

список змін

З версії 2.5.0 Введена. З версії 4.4.0 Added the $ tagnames parameter.

Код get shortcode regex: wp-includes / shortcodes.php WP 5.2.2

<? Php function get_shortcode_regex ($ tagnames = null) {global $ shortcode_tags; if (empty ($ tagnames)) {$ tagnames = array_keys ($ shortcode_tags); } $ Tagregexp = join ( '|', array_map ( 'preg_quote', $ tagnames)); // WARNING! Do not change this regex without changing do_shortcode_tag () and strip_shortcode_tag () // Also, see shortcode_unautop () and shortcode.js. // phpcs: disable Squiz.Strings.ConcatenationSpacing.PaddingFound - do not remove regex indentation return '\\ [' // Opening bracket. '(\\ [?)' // 1: Optional second opening bracket for escaping shortcodes: [[tag]]. "($ Tagregexp)" // 2: Shortcode name. '(?! [\\ w-])' // Not followed by word character or hyphen. '(' // 3: Unroll the loop: Inside the opening shortcode tag. '[^ \\] \\ /] *' // Not a closing bracket or forward slash. '(?:'. '\\ / ( ?! \\]) '// A forward slash not followed by a closing bracket.' [^ \\] \\ /] * '// not a closing bracket or forward slash.') *? '.') ' . '(?:'. '(\\ /)' // 4: Self closing tag .... '\\]' // ... and closing bracket. '|'. '\\]' // Closing bracket. '(?:'. '(' // 5: Unroll the loop: Optionally, anything between the opening and closing shortcode tags. '[^ \\ [] * +' // Not an opening bracket. '(? : '.' \\ [(?! \\ / \\ 2 \\]) '// An opening bracket not followed by the closing shortcode tag.' [^ \\ [] * + '// Not an opening bracket . ') * +'. ')'. '\\ [\\ / \\ 2 \\]' // Closing shortcode tag. ')?'. ')'. '(\\]?)'; // 6: Optional second closing brocket for escaping shortcodes: [[tag]] // phpcs: enable}

cвязана функції

З розділу: Шорткоди

Danya 50

Програміст фрілансер. Кодінгом на PHP займаю з 2008 року.

Echo get_shortcode_regex (array ( 'mytag')); //> \ [(\ [?) (Mytag) (?! [\ W -]) ([^ \] \ /] * (?: \ / (?! \]) [^ \] \ /] * ) *?
Lt;?

Новости

Banwar.org
Наша совместная команда Banwar.org. Сайт казино "Пари Матч" теперь доступен для всех желающих, жаждущих волнения и азартных приключений.