add_shortcode( $tag, $callback )
Функція реєструє новий шорткод у темі або плагіні.
$tag
:
(string)
Required
$callback
:
(callable)
Optional
$atts
:
(array)
$content
:
(string)
$shortcode_tag
:
(string)
Callback функція не повинна нічого виводити, тільки повертати значення
Шорткод, який покаже статичний текст.
<?php
function wp_teka_basic_shortcode() {
return "Hello, this is a basic shortcode!";
}
add_shortcode('wp_teka_basic', 'wp_teka_basic_shortcode');
// Приклад використання WP редакторі - [wp_teka_basic]
// Приклад використання у коді - <?php echo so_shortcode('[wp_teka_basic]');?>
<?php
function wp_teka_custom_message_shortcode($atts) {
$atts = shortcode_atts(
array(
'message' => 'Дефолтна записка'
),
$atts
);
return "Ваше повідомлення: " . esc_html($atts['message']);
}
add_shortcode('wp_teka_custom_message', 'wp_teka_custom_message_shortcode');
// Згенерований шорткод - [wp_teka_custom_message]
// Приклад використання WP редакторі - [wp_teka_custom_message message="Хелоу Ворлд"]
Шорткод, який обгортає вміст, наданий користувачем.
<?php
function wp_teka_wrap_content_shortcode($atts, $content = null) {
return '<div class="wp-teka-wrap">' . do_shortcode($content) . '</div>';
}
add_shortcode('wp_teka_wrap', 'wp_teka_wrap_content_shortcode');
// Приклад використання у WP редакторі - [wp_teka_wrap]Цей контент буде обгорнуто в дів з потрібними класами[/wp_teka_wrap]
<?php
function wp_teka_datetime_shortcode() {
return "Current date and time is: " . date('Y-m-d H:i:s');
}
add_shortcode('wp_teka_datetime', 'wp_teka_datetime_shortcode');
// Приклад використання у WP редакторі - [wp_teka_datetime]
// Приклад використання у коді - <?php echo so_shortcode('[wp_teka_datetime]');?>
Це найбільш популярний варіант, як я додаю кастомний блок на сайт клієнта, якщо у нього до цього був пейдж білдер
<?php
function wp_teka_shortcode_function( $atts ) {
$attributes = shortcode_atts( array(
'title' => false,
'limit' => 4,
), $atts );
ob_start();
// Додаємо темплейт парт з аругментами ($args параметер був доданий у WordPress v5.5.0)
get_template_part( 'template-parts/wp-teka-the-shortcode-template', null, $attributes );
return ob_get_clean();
}
add_shortcode( 'wp_teka_shortcode_template_part', 'wp_teka_shortcode_function' );