Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wp_localize_script multiple times from Shortcode

I have a shortcode [tips] in which at the end I'm doing:

wp_enqueue_script( "tips", plugins_url( "/tips/js/tips.js", PATH ), array("jquery"), TIPS_VERSION, true );
wp_localize_script( "tips", "objTips", $objTips );

If there are multiple [tips] shortcodes on the same Page I'd like to pass one objTips object with the $objTips data from all the shortcodes from that Page.

Right now it's outputting var objTips = {...} twice (or more), so JavaScript file tips.js only recognizes the last one. I'd like it to be something like var objTips = [{...},{...},{...},...];

like image 409
Nurgiel Avatar asked Nov 04 '25 05:11

Nurgiel


1 Answers

It's possible to have a static counter inside the shortcode function as shown here: Count how many times shortcode is called and display different content in each « WordPress.org Forums.

The shortcode declaration would add the tips to a JS array:

add_shortcode( 'tips',  function ( $atts, $content = null, $shortcode ) {
    static $count = 0;

    # https://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php
    $return = <<<JS
        <script> 
            objTips[$count] = "$content";
        </script>
JS;
    $count++;
    return $return;
});

add_action( 'wp_enqueue_scripts', function() {
    wp_enqueue_script(  'tips-script', plugin_dir_url( __FILE__ ) . '/tips.js', array( 'jquery' ) );
});

And the enqueued JS file would initialize that array and show the final result on document load:

var objTips = [];

jQuery( document ).ready( function( $ ) { 
    console.log(objTips);
});

A page with multiple shortcodes would look like this:

[tips]one[/tips]

[tips]two[/tips]

[tips]and three[/tips]

Result on browser console:


like image 65
brasofilo Avatar answered Nov 06 '25 20:11

brasofilo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!