I got this geolocation working but if I put it in WordPress it stops working. What's wrong with this?
http://jsfiddle.net/spzg5oL8/3/
$.get("http://freegeoip.net/json/", function (response) {
$("#ip").html("IP: " + response.ip);
//$("#country_code").html(response.country_code);
document.getElementsByClassName(response.country_code)[0].style.display = "block";
}, "jsonp");
This will not work in WordPress for one reason (for sure), and another reason (potentially):
First, you cannot use the $
for jQuery in WordPress. WordPress loads jQuery in "no-conflict" mode, which means you have to use jQuery
, OR wrap this in a document ready method to "inject" the $
:
jQuery(function($) {
$.get("http://freegeoip.net/json/", function (response) {
$("#ip").html("IP: " + response.ip);
//$("#country_code").html(response.country_code);
// Why don't you use jQuery here, for simplicity?
// $('.' + response.country_code).style('display', 'block');
document.getElementsByClassName(response.country_code)[0].style.display = "block";
}, "jsonp");
});
Second, you have to be sure that jQuery is loaded on your WordPress site. Whatever you do, do not just hard-code a link to jQuery in the header of the site, but rather, in the functions.php
file for the theme (or plugin) add the below php:
add_action('wp_enqueue_scripts', 'load_my_scripts');
function load_my_scripts() {
wp_enqueue_script('jquery');
}
Adding to what @cale_b said, you can see the call to jQuery.noConflict();
as the last line of Wordpress's jQuery file:
/wp-includes/js/jquery/jquery.js
I haven't found anything explicitly in the documentation, but seeing it in the code helps to know what's happening.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.