Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

484
Vistas
Pass php variable to javascript (variable in javascript is undefined)

I'm trying to pass php variables to js like:

    function wpdocs_theme_name_scripts()
    {
       if (is_checkout()) {
            wp_enqueue_script('script-to-pass', get_stylesheet_directory_uri() . '/assets/js/chkt-script.js', ['jquery'], $GLOBALS['dynamic_version'], '');
       }

    }
    add_action('wp_print_scripts', 'wpdocs_theme_name_scripts');


   $chktValStrings = array(
     'phoneEmpty'    => __( 'Phone empty', 'flatsome' ),
     'phoneFormat'   => __( 'Phone format', 'flatsome' ),
  );


 wp_add_inline_script( 'script-to-pass', 'var php_vars = ' . wp_json_encode( $chktValStrings ), 'before' );

//this also didn't work
//wp_localize_script( 'script-to-pass', 'php_vars', $chktValStrings);

and then call in js:

    (function ($) {

      console.log(php_vars.phoneEmpty)
      console.log(php_vars.phoneFormat)

    }(jQuery))

I also tryed with:

     jQuery(document).ready(function ($) {

      console.log(php_vars.phoneEmpty)
      console.log(php_vars.phoneFormat)
     });

And in both scenarios php_vars is undefined. Script is loading ok also other code in this script works like it should.

Dynamic version in enqueue_script is version which is used on all page when we make changes

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

The wp_add_inline_script function must be called inside the wp_print_scripts . move it to the wpdocs_theme_name_scripts function.

 function wpdocs_theme_name_scripts() { if (!is_checkout()) { return; } wp_enqueue_script('script-to-pass', get_stylesheet_directory_uri() . '/assets/js/chkt-script.js', ['jquery'], $GLOBALS['dynamic_version'], ''); $chktValStrings = array( 'phoneEmpty' => __('Phone empty', 'flatsome'), 'phoneFormat' => __('Phone format', 'flatsome'), ); wp_add_inline_script('script-to-pass', 'var php_vars = ' . wp_json_encode($chktValStrings), 'before'); //this also should work //wp_localize_script( 'script-to-pass', 'php_vars', $chktValStrings); } add_action('wp_print_scripts', 'wpdocs_theme_name_scripts');
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda