• Resolved Nokaa

    (@nokaa)


    Hi,

    I wanted to get two parameters (‘id’ and ‘value’) entered in a shortcode of an article, in order to use it in a JS script :
    I created a plugin for that, here’s the code :

    <?php
    /*
    Plugin Name: Devisplus Select Default
    Description: Change a default value 
    Author: -
    */
    
    wp_register_script( 'dpe_select_default_script', plugin_dir_url( __FILE__ ) . 'dpe-select-default.js', array('jquery'), '1.0' );
    
    function dpe_get_atts($atts){
      extract(
        $array_variable = shortcode_atts(array(
            'id' => 'main',
            'value' => 'TestValue',
          ),
          $atts
        )
      );
     
    }
    
    add_shortcode('dpe-sd', 'dpe_get_atts');
    
    wp_enqueue_script( 'dpe_select_default_script' );
    wp_localize_script('dpe_select_default_script', 'dpe_sd', $array_variable);

    I can well use $id and $value to get the values of the shortcodes atts. It works fine in PHP. My script is also executed but can’t recognize the object I mention in the “localize” function. It returns this issue :

    TypeError: dpe_sd is null

    Here’s the JS file :

    var id = dpe_sd.id;
    var value = dpe_sd.value;
    
    jQuery(document).ready( function( $ ){
    	
    	console.log('ok');
    	
    });

    Can someone help me with this problem ?

    Thank you in advance,

    Nokaa

Viewing 1 replies (of 1 total)
  • Thread Starter Nokaa

    (@nokaa)

    Finally found my error. The script need to be localized and enqueued in the shortcode function, like this :

    add_action('wp_enqueue_scripts', 'register_scripts');
    
    function register_scripts(){
    	wp_register_script( 'dpe_select_default_script', plugin_dir_url( __FILE__ ) . 'dpe-select-default.js', array('jquery'), '1.0', true);
    }
    
    function dpe_get_atts($atts){
    	extract(
    		$array_variable = shortcode_atts(array(
    			'id' => 'test',
    			'value' => 'testValue',
    		),
    		$atts
    		)
    	);
      
    	wp_enqueue_script('dpe_select_default_script'); 
    	wp_localize_script('dpe_select_default_script', 'dpe', $array_variable);
    }
    
    add_shortcode('dpe-sd', 'dpe_get_atts');
Viewing 1 replies (of 1 total)
  • The topic ‘Localize variables from shortcode for JS doesn’t work’ is closed to new replies.