Accessing PHP variables in JavaScript is very important requirement especially when developers deal with Ajax implementation in the WordPress development. Fortunately, WordPress has solved this beautifully by providing an easy to use function i.e. wp_localize_script

Following code will help you to understand that how can we pass PHP variables to JavaScript in WordPress?

PHP Code – functions.php

/** Register Scripts. */
add_action( 'wp_enqueue_scripts', 'theme_register_scripts', 1 );
function theme_register_scripts() {

  /** Register JavaScript Functions File */
  wp_register_script( 'functions-js', esc_url( trailingslashit( get_templat  e_directory_uri() ) . 'functions.js' ), array( 'jquery' ), '1.0', true );

  /** Localize Scripts */
  $php_array = array( 'language' => get_bloginfo( 'language' ), 'version' => get_bloginfo( 'version' ) );
  wp_localize_script( 'functions-js', 'php_array', $php_array );

}

/** Enqueue Scripts. */
add_action( 'wp_enqueue_scripts', 'theme_enqueue_scripts' );
function theme_enqueue_scripts() {

  /** Enqueue JavaScript Functions File */
  wp_enqueue_script( 'functions-js' );

}

JavaScript Code – functions.js

(function($) {

  $(document).ready(function(){
    console.log( php_array.language );
    console.log( php_array.version );		
  });

})(jQuery);

We have written the above code according to WordPress Codex,

IMPORTANT!: wp_localize_script() MUST be called after the script it’s being attached to has been enqueued or registered. It doesn’t put the localized script in a queue for later scripts.

Reference:

You may also be interested to learn about add custom field to category, more tag for pages, exclude category from wordpress loop and get all taxonomy terms.

Leave a Reply