How do I use WordPress PHP functions in my Javascript code?

Let’s say I want to run the javascript function launchMyPlugin() only on post detail pages. At first, I was doing something like this:

myPlugin.js

if ( is_single() ) {
    launchMyPlugin();
}

However, this obviously does not work since is_single() is a php function. What is the right way to do this then? Do I need to add the condition to my .php file instead? Thanks!

1 Answer
1

You can check is_single before enqueue the js file

add_action('wp_enqueue_scripts', '_enqueue');

function _enqueue(){
   if(is_single(){
       wp_enqueue_script(......);
   }
}

Leave a Comment