Adding api object to wp_localize_script

Hi im having some trouble adding the following to wp_localize_script, im unsure of best practice of where to put the following as currently it is not getting added to the wp object?

$theme_urls = array(
‘theme_url’ => get_stylesheet_directory_uri(),
‘root’ => home_url(),
‘api’ => home_url() . ‘/wp-json/wp/v2’
);
//after wp_enqueue_script
wp_localize_script( ‘[what script do i add here?]’, ‘wp’, $theme_urls );

can someone give me an example of how i would turn this into a wp sage friendly function?

The script you add here is the one that will be accessing these variables. WordPress will “localize” the script every time that it’s called and so if you register a script, localize it and then only enqueue it on the contact page then the variables you added to it will also only be displayed on the contact page.

I wanted to localize the permalink of a page called “Interviews” so that I could use JavaScript to hijack clicks on links and redirect users only if they had JS enabled and so I modified /lib/setup.php to the following:

function assets() {
  wp_enqueue_style('sage/css', Assets\asset_path('styles/main.css'), false, null);

  if (is_single() && comments_open() && get_option('thread_comments')) {
    wp_enqueue_script('comment-reply');
  }

  wp_enqueue_script('sage/js', Assets\asset_path('scripts/main.js'), [], null, true);

  // Localize the script with new data
  $localized_array = array(
    'permalink' => get_permalink(get_page_by_title('Interviews'))
  );
  wp_localize_script( 'sage/js', 'interviews', $localized_array );

}

add_action('wp_enqueue_scripts', __NAMESPACE__ . '\\assets', 100);

Then in my main.js (the one that I localized) I used this:

$('.Interview--excerpt .Button').on('click', function(e) {

  if ($(window).width() >= 767) {
    e.preventDefault();
    var url = interviews.permalink;
    var id = $(this).parents('.Interview').data('id');
    window.location = url + '?id=' + id;
  }
  
});
2 Likes

thank you paul_tibbetts, So i’m my case i want to add to an existing WP object, and my JS is in the ‘common’ variable in main.js.

in addition i have added the following into setup.php

if (is_single() && comments_open() && get_option('thread_comments')) {
wp_enqueue_script('comment-reply');
  }

  wp_enqueue_script('sage/js', Assets\asset_path('scripts/main.js'), ['jquery'], null, true);


  // Localize the script with new data
  $theme_urls = array(
      'theme_url' => get_stylesheet_directory_uri(),
  'root' => home_url(),
  'api' => home_url() . '/wp-json/wp/v2'
  );
  wp_localize_script( 'sage/js', 'common', $theme_urls );


}

my problem is that is still doesnt seem to get added to the object if i type ‘wp’ in the console.
Any ideas?

strike that…i got it working…i changed common with ‘wp’ and got it working!
thanks for your help!!

2 Likes