Support » Developing with WordPress » Pass shortcode attributes and extra data to JS with wp_localize_script

  • Resolved Word

    (@hajar2901)


    I wanted to add extra data to shortcode attributes array and pass the array to js with wp_localize_script, the data is added and the array is sent, but it’s also printed as :

    <script>var custom = {"status":"new","type":"depend","url":"https:\/\/www.exemple.com"};</script>

    My code in functions.php :

        function resources() {
            wp_register_script('custom_js', get_stylesheet_directory_uri().'/assets/js/custom.js', array('jquery'), '', TRUE);
            wp_register_style( 'custom_css', get_stylesheet_directory_uri() . '/assets/css/custom.css', array(), '1', 'all' );
        }
        add_action( 'init', 'resources' );
        
        function new_shortcode($atts){
           
            if (!empty($atts)) {
                $atts['url'] = MAIN_URL;
                wp_localize_script('custom_js', 'custom', $atts);
            }
            wp_enqueue_script("custom_js");
            wp_enqueue_style("custom_css");
            
        }
        add_shortcode('custom', 'new_shortcode');

    Is there another way to do this without printing the data in script tag ?

    • This topic was modified 3 years, 4 months ago by Word.
    • This topic was modified 3 years, 4 months ago by Word.
Viewing 4 replies - 1 through 4 (of 4 total)
  • Moderator bcworkz

    (@bcworkz)

    I’m unaware of any way to pass PHP data to JS other than by outputting it somewhere. Since you marked this topic resolved, did you find an alternative method? I’m curious to know what that is. Thanks.

    Thread Starter Word

    (@hajar2901)

    I found some way like using Ajax instead of wp_localize_script() but I didn’t think that it will be useful in my case.

    Ajax

    What I wanted at first is to not use inline Js because it will let the informations used in the shortcode easily accessible, anyway at the end I decided to encode the shortcode data in php and pass it to js file then decode it there to use it in other stuff.

    Details

    Moderator bcworkz

    (@bcworkz)

    OK, thanks. So your objection to outputting the data was because it was plain text that anyone could read if they inspected the page HTML source? By obfuscating the data with base64, the fact something is output is no longer an issue? You do realize that base64 will not prevent a determined user from decoding the data, right? It will certainly stymie the majority of users, but it cannot be considered as completely secure. Anything sent to a browser cannot be considered secure no matter what you do to encode it.

    Thread Starter Word

    (@hajar2901)

    Yes, the shortcode doesn’t have like super dangerous data, but just for nosy people, I am satisfied this way 🙂

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Pass shortcode attributes and extra data to JS with wp_localize_script’ is closed to new replies.