Site icon Hip-Hop Website Design and Development

Find out how to cross a php variable to js inside a template?

I’m attempting to cross a variable from the template to js, however with no luck.

I’ve tried utilizing wp_localize_script, and it appears to be working tremendous when hooked up to wp_enqueue_scripts motion, however it doesn’t work when referred to as from inside template. Do my solely resort is to make use of HTML & data- for dealing with this?

It will be that nice although, since I’m passing the entire wp_query there.

My operate is mainly a wrapper on a customized WP_Query that enables load extra performance on a number of loops.

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


 // this operate is later referred to as within the template
operate get_list($query_args) {
    if ( is_array( $query_args ) ) {
        $the_query = new WP_Query( $query_args ); 
    } 

    //...some extra code


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

Replace
It appears the problem could be in localizing a number of scripts. If you happen to register the script to load within the footer, model with out including an $occasion to load_more_params appears to work.