1

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?

2
  • 1
    Your first attempt should be working. Make sure plugins_url() actually writes something and doesn't just returns the value. Try replacing plugins_url() with echo 'hello' and see if it works. Commented Feb 13, 2018 at 5:45
  • Thanks for your time. I changed accordingly and now I can see <?php echo 'hello'; ?> in my console log Commented Feb 13, 2018 at 5:50

2 Answers 2

2

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 );
});
Sign up to request clarification or add additional context in comments.

3 Comments

Would you say in more detail please. It seems to me it will be good practice you are mentioning.
@AbdusSattarBhuiyan please check added an example. You'll get more details if you check those function doc. And yes it's best practice.
Agreed this is the best method rather than using the hack in your question.
0

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);
 });

1 Comment

Now I can see <?php echo plugins_url(); ?> in console log

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.