Reputation: 3074
I tried all possible ways to write php code inside a jquery code. Here is my code snippet:
$('body').on('click', '.add_more', function(){
var plugin_dir = "<?php plugins_url(); ?>";
console.log(plugin_dir);
});
Even I tried as follows:
$('body').on('click', '.add_more', function(){
var plugin_dir = <?php plugins_url(); ?>;
console.log(plugin_dir);
});
I am writing this code inside a wordpress plugin php file. I apologize if this question is duplicate. It kills my day. Any idea?
Upvotes: 1
Views: 987
Reputation: 623
Instead of assigning value that way you can use wp_localize_script()
or wp_add_inline_script()
and create a plugin configuration JS object to use that everywhere.
PHP file
add_action( 'wp_enqueue_scripts', function() {
wp_enqueue_script(
'script-handle',
'your-script-uri/script.js',
array( 'jquery' ),
'version',
true
);
wp_localize_script(
'script-handle',
'pluginNameSpace',
array(
'url' => plugins_url()
)
);
} );
JS file
$('body').on('click', '.add_more', function(){
console.log( pluginNameSpace.url );
});
Upvotes: 2
Reputation: 2314
You just need to echo the plugins_url()
$('body').on('click', '.add_more', function(){
var plugin_dir = "<?php echo plugins_url(); ?>";
console.log(plugin_dir);
});
Upvotes: 0