Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

498
Views
Pase la variable php a javascript (la variable en javascript no está definida)

Estoy tratando de pasar variables php a js como:

 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);

y luego llame a js:

 (function ($) { console.log(php_vars.phoneEmpty) console.log(php_vars.phoneFormat) }(jQuery))

También probé con:

 jQuery(document).ready(function ($) { console.log(php_vars.phoneEmpty) console.log(php_vars.phoneFormat) });

Y en ambos escenarios, php_vars no está definido. El script se está cargando bien, también otro código en este script funciona como debería.

La versión dinámica en enqueue_script es la versión que se usa en todas las páginas cuando hacemos cambios

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

La función wp_add_inline_script debe llamarse dentro del wp_print_scripts . muévalo a la función wpdocs_theme_name_scripts .

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!