Utilizzo di shortcode con bxslider

Aug 20 2020

Quindi sto costruendo uno shortcode in modo da poterlo usare con bxSlider (https://bxslider.com/examples/image-slideshow-captions/) ma per qualche motivo non riesco a far funzionare il mio javascript.

Ecco l'esempio del mio shortcode:

[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]

Ecco il codice che ho finora:

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');

Ecco come vengono attualmente visualizzati gli 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>

Per qualche motivo, sembra che il tag script non venga rilevato affatto, poiché non vedo affatto un riferimento nella mia console.

Aggiornare:

Risposte

2 FluffyKitten Aug 20 2020 at 01:54

Il problema è con i <p>tag vuoti prima degli shortcode. Questo è un problema comune con gli shortcode inseriti nell'editor WP. Ci sono alcuni modi per affrontare questo problema:

1. autop - Puoi cambiare la priorità di autopeseguire in seguito, aggiungendolo al tuo functions.php:

remove_filter( 'the_content', 'wpautop' );
add_filter( 'the_content', 'wpautop' , 99);

2. Rimuovi i tag vuoti Se questo influisce su altri output, puoi usare questa funzione per rimuovere i <p></p>tag vuoti dal tuo output:

function my_stripemptytags($content){ $pattern = "/<p[^>]*><\\/p[^>]*>/"; // remove empty p tags
    return preg_replace($pattern, '', $content); 
}
add_filter( 'the_content', 'my_stripemptytags', 100 );

ID univoco mancante

Inoltre non stai ricevendo un ID univoco perché questo codice sta cercando di generarlo per titleessere passato nello shortcode:

$atts = shortcode_atts( [ 'id' => '', ], $atts, 'slider');

// NOTE: THERE IS NO $atts['title'] $id = $atts['id'] ?: rawurldecode(sanitize_title($atts['title']));

Tuttavia non stai passando o controllando un titleattributo nel tuo shortcode.

Se stai cercando di utilizzare l'ID del post, puoi ottenerlo in questo modo:

global $post; $title = $post->title;
Unbywyd Aug 20 2020 at 01:29

Non dovresti usare shortcode all'interno di uno shortcode, anche se sembra funzionare, ha delle conseguenze l'editor di wordpress elabora il contenuto e converte tutte le interruzioni di riga in html e altro ancora. Questo non garantisce che riceverai la struttura di cui hai bisogno.

ma se vuoi una soluzione, allora c'è (non lo consiglio)

1.) correggi prima il codice (segui i commenti)

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;
}

E usa i tuoi codici brevi ma senza uno spazio

[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]

Ho controllato che restituisca quello che ti serve


Risultato:

Codice completo

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');
JamesRyvenValeii Aug 20 2020 at 02:11

Sto ottenendo una presentazione funzionante usando il tuo codice, con alcuni parametri e output aggiunti:

    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');
    ?>

Chiamato tramite:

    [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]