2013-04-15 14 views
5

Ho il seguente codice nel mio tema functions.php ma quando chiamo console.log(pw_script_vars); la variabile è undefined. Cosa mi sono perso?wp_localize_script non funziona

function mytheme_enqueue_scripts(){ 
    wp_enqueue_script('jquery'); 

} 
add_action('wp_enqueue_scripts', 'mytheme_enqueue_scripts'); 

function pw_load_scripts() { 

    wp_enqueue_script('pw-script'); 
    wp_localize_script('pw-script', 'pw_script_vars', array(
      'alert' => __('Hey! You have clicked the button!', 'pippin'), 
      'message' => __('You have clicked the other button. Good job!', 'pippin') 
     ) 
    ); 


} 
add_action('wp_enqueue_scripts', 'pw_load_scripts'); 

risposta

12

Non ha incluso alcun file javascript con il vostro wp_enqueue_script.

function pw_load_scripts() { 

    wp_enqueue_script('pw-script', get_template_directory_uri() . '/test.js'); 
    wp_localize_script('pw-script', 'pw_script_vars', array(
      'alert' => __('Hey! You have clicked the button!', 'pippin'), 
      'message' => __('You have clicked the other button. Good job!', 'pippin') 
     ) 
    ); 


} 
add_action('wp_enqueue_scripts', 'pw_load_scripts'); 

Creare un file vuoto chiamato test.js nella directory tema e che funzionerà.

Se poi si guarda il codice sorgente si vedrà:

<script type='text/javascript'> 
/* <![CDATA[ */ 
var pw_script_vars = {"alert":"Hey! You have clicked the button!","message":"You have clicked the other button. Good job!"}; 
/* ]]> */ 
</script> 

È possibile digitare pw_script_vars.alert nella console per ottenere il messaggio "Hey! You have clicked the button!".

+0

Grazie per la risposta, ma la mia intenzione era quella di passare alcuni array php in jquery dove posso fare appello su ogni pagina del mio modello ... –

+0

Questo è esattamente ciò che faceva il codice sopra. Hai avuto problemi? – RRikesh

+0

Ho ottenuto lo script da: http://papermashup.com/jquery-iphone-style-ajax-switch/ e ho creato: \t wp_enqueue_script ('ajax-switch', get_bloginfo ('template_url'). '/ Include/ajaxswitch /jquery.iphone-switch.js ', false, false); \t globale $ utente corrente; \t wp_localize_script ('ajax-switch', 'ajax_switch', array ( \t \t \t \t 'post_status' => get_user_meta ($ current_user-> ID, '_fbpost_status', true), \t \t \t \t 'TemplateURL' = .> get_template_directory_uri() '/ include/ajaxswitch /' \t \t \t \t) \t \t); E la ringrazio molto, la seconda cosa è che in quei file php ho bisogno di includere le variabili wordpress e la libreria php. Come? –

1

Si potrebbe anche provare a localizzare jQuery senza la necessità di creare ulteriori file JS vuoti.

wp_localize_script('jquery', 'pw_script_vars', array(
     'alert' => __('Hey! You have clicked the button!', 'pippin'), 
     'message' => __('You have clicked the other button. Good job!', 'pippin') 
    ) 
); 

Funziona come un incantesimo per me. Spero che sia d'aiuto.