How to use php in main.js?

like the topic title, I would to use php in main.js.

for include template path or WPML plugin string for translation, I try to add

var templatePath = <?= get_template_directory_uri() ?>;
var exampleString = <?= __('Example text', 'my-theme') ?>;

but they not work…

How is the correct way to do?

Thank you!

I would use a php function to put data to the right places and echo out all JS code once done. But i’m not a php pro so there may be better ways of doing it. :smile:

This would not put the js code in main.js though so… may not be what you want.

Something along the lines can get you an idea:

function custom_js() { 
  $templatePath = get_template_directory_uri();
  $exampleString = __('Example text', 'my-theme');
  echo '<script> 
   var templatePath = '. $templatePath .';
   var exampleString = '. $exampleString .';

You can use hooks to position it where you want.

1 Like