Is there any possibility to pass some PHP variables in javascript so I can use them later?
Only in single.php
.
I heard about wp_enqueue_scripts
but with that it is neccesary to declare a path to a JS file, but I don`t need one.
Is there any possibility to pass some PHP variables in javascript so I can use them later?
Only in single.php
.
I heard about wp_enqueue_scripts
but with that it is neccesary to declare a path to a JS file, but I don`t need one.
You must be logged in to post a comment.
Best practice method
Have a look at
wp_localize_script
, which is meant to do exactly that.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.
In the JS you will then be able to use the passed parameters like so:
[Edit] Your situation
As per your comment
Put the following your theme’s
/js/
folder, create it, if it doesn’t exist.Let’s call the file
fb-response.js
:Then register, enqueue and localize as seen above. Assuming that you have the ID you’d like to pass in let’s say
$fb_id
:N.B. Obviously, the above is assuming this is in a theme. If we’re talking “plugin”, alter locations accordingly.
https://developer.wordpress.org/reference/functions/wp_add_inline_script/ should be a preferred option nowadays
EDIT:
From the docs above:
So that you first enqueue the script, and then pass the variables
Yet this code simply generates the following
In my case, I simply expose the data I need directly writing the JavaScript code (in the template) and using a global JS variable with a specific name (haven’t found a better way) (using Timber, pure PHP should be equivalent)
Having read your comment, I understand you’d like to do something like this: