I am trying to find out if you can enqueue a script in Wordpress that has php variables within it. If this is possible how would it be done?
I have tried this, however I get errors.
function my_scripts_method() {
wp_enqueue_script(
'custom-script',
get_stylesheet_directory_uri() . '/masonry.php',
array( 'jquery' )
);
}
add_action( 'wp_enqueue_scripts', 'my_scripts_method' );
Your question is a bit ambiguous.
include_once
or require_once
in your PHP file.If you want to include JavaScript file, use wp_enqueue_script
. Your code should be something like:
wp_enqueue_script(
'custom-script',
get_stylesheet_directory_uri() . '/masonry.js',
array( 'jquery' )
);
Moreover, if you want to use PHP variables inside a JS file, use wp_localize_script
.
After enqueue, use the following line:
$name = "my_name";
$params = array('name' => $name);
wp_localize_script( 'custom-script', 'OBJECT', $params );
Inside your masonry.js, use OBJECT.name
to get the value.
<?php
header('Content-type: application/javascript');
$php = 'Hello World';
echo "alert('$php');";
And then link/enqueue your php as if it was a javascript file:
wp_enqueue_script(
'custom-script',
get_stylesheet_directory_uri() . '/masonry.php',
array( 'jquery' )
);
wp_add_inline_script
function to print the inline code.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With