Использование шорткодов с bxslider
Итак, я создаю шорткод, чтобы использовать его с bxSlider (https://bxslider.com/examples/image-slideshow-captions/), но по какой-то причине я не могу работать с javascript.
Вот пример моего шорткода:
[slider]
[slide headline="Hack Your Newsfeed" image="/wp-content/uploads/2019/10/M2020DayOne.jpg" body="<p>Test.</p>" link="Learn How Now|https://www.howtogeek.com/665935/how-to-sort-your-facebook-feed-by-most-recent/"]
[slide headline="Branch Out" image="/wp-content/uploads/2019/10/M2020DayOne.jpg" body="<p>Test</p>" link="Facebook|https://facebook.com" link="Instagram|https://instagram.com"]
[/slider]
Вот код, который у меня есть:
function slider_wrapper_shortcode($atts, $content = null)
{
$atts = shortcode_atts( [ 'id' => '', ], $atts, 'slider');
$id = $atts['id'] ?: rawurldecode(sanitize_title($atts['title'])); $cleaned_content = wpautop(trim($content)); $output = '<div id="bxslider' . $id . '" class="bxslider">'; $output .= do_shortcode($cleaned_content); $output .= '</div>';
$output .= '<script type="text/javascript"> jQuery(document).ready(function() { jQuery(".bxslider").bxSlider({ pager: false, auto: true, pause: 3000, captions: false, }) }) </script>'; return $output;
}
add_shortcode('slider', 'slider_wrapper_shortcode');
function slide_item_shortcode($atts, $content = null)
{
extract(shortcode_atts([
"image" => 'image',
], $atts) ); return '<div><img src="' . home_url(esc_url($image)) . '" alt="" /></div>';
}
add_shortcode('slide', 'slide_item_shortcode');
Вот как отображаются шорткоды в настоящее время:
<div id="bxslider" class="bxslider">
<p></p><div><img src="https://*****.com.local/wp-content/uploads/2019/10/M2020DayOne.jpg" alt=""></div>
<p></p>
<p></p><div><img src="https://*****.com.local/wp-content/uploads/2019/10/M2020DayOne.jpg" alt=""></div>
<p></p>
</div>
По какой-то причине похоже, что тег скрипта вообще не обнаруживается, так как я вообще не вижу ссылки в своей консоли.
Обновить:

Ответы
Проблема заключается в пустых <p>
тегах перед шорткодами. Это обычная проблема с короткими кодами, введенными в редактор WP. Есть несколько способов решить эту проблему:
1. autop - Вы можете изменить приоритет autop
для запуска позже, добавив это в свой functions.php:
remove_filter( 'the_content', 'wpautop' );
add_filter( 'the_content', 'wpautop' , 99);
2. Удалите пустые теги p. Если это повлияет на другой вывод, вы можете использовать эту функцию для удаления пустых <p></p>
тегов из вывода:
function my_stripemptytags($content){ $pattern = "/<p[^>]*><\\/p[^>]*>/"; // remove empty p tags
return preg_replace($pattern, '', $content);
}
add_filter( 'the_content', 'my_stripemptytags', 100 );
Отсутствует уникальный идентификатор
Вы также не получаете уникальный идентификатор, потому что этот код пытается сгенерировать его из title
передачи в шорткод:
$atts = shortcode_atts( [ 'id' => '', ], $atts, 'slider');
// NOTE: THERE IS NO $atts['title'] $id = $atts['id'] ?: rawurldecode(sanitize_title($atts['title']));
Однако вы не передаете и не проверяете title
атрибут в своем шорткоде.
Если вы хотите использовать идентификатор сообщения, вы можете получить его так:
global $post; $title = $post->title;
Вы не должны использовать шорткоды внутри шорткода, даже если он кажется работоспособным, это имеет последствия: редактор wordpress обрабатывает контент и преобразует все разрывы строк в HTML и т. Д. Это не гарантирует, что вы получите нужную вам конструкцию.
но если вам нужно решение, то есть (не рекомендую)
1.) сначала исправьте свой код (следуйте комментариям)
function slider_wrapper_shortcode($atts, $content = null)
{
$atts = shortcode_atts( [ 'id' => '', ], $atts, 'slider');
// You need to use isset or empty methods for data validation
// (you had a mistake here, you didn't have a title in the attributes of shortcode
$title = isset($atts['title']) ? $atts['title'] : ""; // same $id = !empty($atts['id']) ? $atts['id'] : rawurldecode(sanitize_title($title)); // don`t use wpautop method $cleaned_content = trim($content); // wpautop $output = '<div id="bxslider_' . $id . '" class="bxslider">'; $output .= do_shortcode($cleaned_content); $output .= '</div>';
$output .= '<script type="text/javascript"> // Wrap your code (function($) {
$(document).ready(function() { // Check if plugin exists if ($.fn.bxSlider) {
// don`t use class, you must use a unique id
$("#bxslider_'.$id.'").bxSlider({
pager: false,
auto: true,
pause: 3000,
captions: false,
})
}
});
})(jQuery);
</script>';
return $output;
}
И используйте свои короткие коды, но без единого пробела
[slider][slide headline="Hack Your Newsfeed" image="/wp-content/uploads/2019/10/M2020DayOne.jpg" body="Test." link="Learn How Now|https://www.howtogeek.com/665935/how-to-sort-your-facebook-feed-by-most-recent/"][slide headline="Branch Out" image="/wp-content/uploads/2019/10/M2020DayOne.jpg" body="Test" link="Facebook|https://facebook.com" link="Instagram|https://instagram.com"][/slider]
Я проверил, возвращает то, что вам нужно
Результат:

Полный код
function slider_wrapper_shortcode($atts, $content = null) { $atts = shortcode_atts(
[
'id' => '',
], $atts, 'slider'); $title = isset($atts['title']) ? $atts['title'] : "";
$id = !empty($atts['id']) ? $atts['id'] : rawurldecode(sanitize_title($title));
$cleaned_content = trim($content); // wpautop
$output = '<div id="bxslider_' . $id . '" class="bxslider">';
$output .= do_shortcode($cleaned_content);
$output .= '</div>'; $output .= '<script type="text/javascript">
(function($) { $(document).ready(function() {
// Check if plugin exists
if ($.fn.bxSlider) { // don`t use class, you must use a unique id $("#bxslider_'.$id.'").bxSlider({ pager: false, auto: true, pause: 3000, captions: false, }) } }); })(jQuery); </script>'; return $output;
}
add_shortcode('slider', 'slider_wrapper_shortcode');
function slide_item_shortcode($atts, $content = null)
{
extract(shortcode_atts([
"image" => 'image',
], $atts) ); return '<div><img src="' . home_url(esc_url($image)) . '" alt="" /></div>';
}
add_shortcode('slide', 'slide_item_shortcode');
Я получаю работающее слайд-шоу с использованием вашего кода с некоторыми добавленными параметрами и выводами:
function slider_wrapper_shortcode($atts, $content = null)
{
$atts = shortcode_atts( [ 'title' => '', 'id' => '', ], $atts, 'slider');
$id = $atts['id'] ?: rawurldecode(sanitize_title($atts['title'])); $cleaned_content = wpautop(trim($content)); $output = '<div id="bxslider' . $id . '" class="bxslider">'; $output .= do_shortcode($cleaned_content); $output .= '</div>';
$output .= '<script type="text/javascript"> jQuery(document).ready(function() { jQuery(".bxslider").bxSlider({ pager: false, auto: true, pause: 3000, captions: false, }) }) </script>'; return $output;
}
add_shortcode('theslider', 'slider_wrapper_shortcode');
function slide_item_shortcode($atts, $content = null)
{
extract(shortcode_atts([
"image" => '',
"headline" => '',
"body" => '',
"link" => '',
], $atts) ); return '<div> <img src="' . esc_url($atts['image']) . '" alt="" />
<p>'.$atts['headline'].'</p> <p>'.$atts['body'].'</p>
<p>'.$atts['link'].'</p>
</div>';
}
add_shortcode('theslide', 'slide_item_shortcode');
?>
Вызывается через:
[theslider]
[theslide headline="Title" image="https://via.placeholder.com/150" body="<p>Test.</p>" link="Learn How Now|https://www.howtogeek.com/665935/how-to-sort-your-facebook-feed-by-most-recent/"]
[theslide headline="Branch Out" image="https://via.placeholder.com/150" body="<p>Test</p>" link="Facebook|https://facebook.com" link="Instagram|https://instagram.com"]
[/theslider]