Roots Discourse

Including PHP in JavaScript

Hello.

So right now I have a script working when it is written directly into the relevant template. CMS-entered text changes on hover, so I am doing this, which works fine (php variables coming from ACF fields).

    $('.drop1').mouseover(function(){
      $(this).text("<?php echo ($drop1HoverText); ?>");
    });

    $('.drop1').mouseleave(function(){
      $(this).text("<?php echo ($drop1Text); ?>");
    });

But if I try to load this through _main.js - php is not compiled and the text is rendered as php code. Other scripts still work.

So is there a preferred way to do something like this, or should I just keep scripts that need php input loading from the template?

Thanks in advance!

The javascript should be a static, compiled file. You should be able to put your javascript and your css on a cdn and it should have no idea PHP is even a thing. You could pass data to the javascript via data attributes

<button class="drop1" data-hovertext="<?= $drop1HoverText ?>"></button>
$('.drop1').mouseover(function() {
  $(this).text($(this).data('hovertext'));
});
4 Likes

Generally, what I do is use wp_localize_script()

http://codex.wordpress.org/Function_Reference/wp_localize_script

Basically, it’s a way to pass PHP to Javascript, so you don’t need to clutter up your HTML with a bunch of one-off scripts.

It’s relatively straight forward to use, just remember to enqueue your script BEFORE you’ve set up the wp_localize_script for it. So something like this:

wp_enqueue_script('roots_js', get_template_directory_uri() . $assets['js'], array(), null, true);

$js_data = array(
	'some_string' => __( 'Some string to translate', 'plugin-domain' ),
	'a_value' => '10'
);
wp_localize_script( 'roots_js', 'mytheme', $js_data );

Then you could use that in your JavaScript:


var myVar = {
  phpData: mytheme.some_string,
  moreData: mytheme.a_value
}

Edit: Also, data-attributes is another way to go, depending on the data you need to work with.

Edit2: Thanks aitor for mentioning that the localization has to happen after the script is registered/enqueued.

7 Likes

Thanks a bunch kalenjohnson and austin - I will try with data attributes first, but then will circle back to use wp_localize_script, since this is happening in a number of spots on the site.

wp_localize_script is also nice for conditional console output and other env or WP variables, i.e.:

    // scripts.php
    wp_localize_script('roots_js', 'MyConfig', array(
        'debug' => WP_DEBUG,
        'templateDirectoryUri' => get_template_directory_uri(),
      )
    );
    // _main.js
    window.log = function() {
      if(MyConfig.debug) {
        log.history = log.history || [];
        log.history.push(arguments);
        if(this.console){
          console.log( Array.prototype.slice.call(arguments) );
        }
      }
    };
5 Likes

Good call, I like that. Will be trying it out.