Passing PHP Variables to JS using Localize Script

Your code should be in an action callback function:

function wpse186202_enqueue_scripts(){
    wp_enqueue_script( 'stats', get_stylesheet_directory_uri() .'/js/t5-demo.js' , array( 'jquery' ), '1.0.0', true );

    $categories = implode( ', ', wp_list_pluck( get_the_category( get_the_ID() ), 'name' ) ); 
    $datatoBePassed = array(
        'author' =>  get_queried_object()->post_author,
        'category'   => $categories,
        'title'      => single_post_title( '', false )
    );
    wp_localize_script( 'stats', 'php_vars', $datatoBePassed );
}

add_action( 'wp_enqueue_scripts', 'wpse186202_enqueue_scripts' ); //Front end enqueueing
add_action( 'admin_enqueue_scripts', 'wpse186202_enqueue_scripts' ); //Admin enqueueing

The action will call the function at the right moment for it to be enqueued properly. Choose the one that works for where you want it enqueued.

Leave a Comment