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