Friday, February 22, 2019

WordPress | Dynamically reference WordPress site URL in JavaScript | WordPress path url in js script file

During my WordPress development, I often find myself in need of the WP home or blog URL from within the JavaScript code.
Instead of hardcoding url in the JavaScript, we're going to dynamically retrieve the site URL, with a little help in PHP.
<?php
wp_register_script(
    'MY_TAXONOMY_PLUGIN_CORE',
    MY_TAXONOMY_PLUGIN_URL . 'assets/script7.js',
    array('jquery')
);

$params = array(
    'BASE_URL' => MY_TAXONOMY_PLUGIN_URL,
    'ADMIN_URL' => admin_url()
);
wp_localize_script( 'MY_TAXONOMY_PLUGIN_CORE', 'MY_TAXONOMY_PLUGIN_CORE', $params);

wp_enqueue_script('MY_TAXONOMY_PLUGIN_CORE');
And from jQuery
alert(MY_TAXONOMY_PLUGIN_CORE.BASE_URL);

6 comments:

  1. Thanks for sharing this information.

    Apptians is the Best Staffing Company in Delhi and top Resource Augmentation company in Delhi NCR, Noida, Faridabad, Gurgaon, India. Dedicated React JS Developers and React Native developers can be hired from Apptians.

    ReplyDelete
  2. Thank you for sharing this post. Looking forward to reading more.
    WordPress Development Services Delhi/NCR

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. It's a great blog, shares a piece of good information.

    GIEC Global is the leading education and migration consultants in India. We are top Study Abroad consultants for Australia. We are best education consultants for Canada in New Delhi. We also helps people in studying in USA and have been awarded as education consultants for USA in Melbourne and education consultant for UK in India.

    ReplyDelete
  5. Very helpful blog! Thnak you for sharing.

    Alteza is a leading online pharmacy app development company and we address every concern of our clients by providing comprehensive online pharmacy apps for their business needs.

    ReplyDelete
  6. YglobisPdiaho Brenda Alvarez Here
    tisodospgras

    ReplyDelete