A common question asked by many people “Is there any possibility to pass some PHP variables in javascript so I can use them later?” The answer to this question is yes.
First you have a look at wp_localize_script, which is pass variable to javascript file in WordPress.
But it does require previous usage of wp_enqueue_scripts, hence you will need to move your JS to a separate file indeed.
It will be worth those few minutes of effort though, for sure.
function labotrees_scripts() { if ( is_single() ) { wp_register_script( 'your_script_handle', get_template_directory_uri() . '/js/your-script.js', array( /* dependencies*/ ), 1.0, true ); wp_enqueue_script( 'your-script-handle' ); $script_params = array( /* examples */ 'post' => 99, 'users' => array( 1, 20, 2049 ) ); wp_localize_script( 'your-script-handle', 'scriptParams', $script_params ); } } add_action( 'wp_enqueue_scripts', 'labotrees_scripts' );
In the JS you will then be able to use the passed parameters like so
var posts = scriptParams.post; console.log(posts); console.log(scriptParams.users);
Try this hack, if you still need help feel free to contact.