How to pass a php variable to js within a template?


I’m trying to pass a variable from the template to js, but with no luck.

I’ve tried using wp_localize_script, and it seems to be working fine when attached to wp_enqueue_scripts action, but it doesn’t work when called from within template. Do my only resort is to use HTML & data- for handling this?

It would be that great though, since I’m passing the whole wp_query there.

My function is basically a wrapper on a custom WP_Query that allows load more functionality on multiple loops.

function load_more_scripts() {
     wp_register_script( 'loadmore', get_stylesheet_directory_uri() . '/assets/js/myloadmore.js', array( 'jquery' ) );
     wp_enqueue_script( 'my_loadmore' );
 add_action( 'wp_enqueue_scripts', 'load_more_scripts' );

 // this function is later called in the template
function get_list($query_args) {
    if ( is_array( $query_args ) ) {
        $the_query = new WP_Query( $query_args ); 

    //...some more code

    $instance = wp_generate_uuid4();
    wp_localize_script( 'loadmore', 'loadmore_params_' . $instance , array(
            'ajaxurl'      => site_url() . '/wp-admin/admin-ajax.php', // WordPress AJAX
            'posts'        => json_encode( $the_query->query_vars ), // everything about your loop is here
            'current_page' => get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1,
            'max_page'     => $the_query->max_num_pages
        ) );

It seems the issue can be in localizing multiple scripts. If you register the script to load in the footer, version without adding an $instance to load_more_params seems to work.

Runnick 5 years 2018-01-08T08:09:17-05:00 0 Answers 92 views 0

Leave an answer