简体   繁体   中英

wordpress how to implement the php shortcode

I have tried to implement the code which can get the user region when the user open the page but it is not working i have used this code inside the functions.php

function user_region() { 
       $ip = $_SERVER['REMOTE_ADDR'];
       $details = json_decode(file_get_contents("http://ipinfo.io/{$ip}"));
        return '<div class="user-region">'.$details->region.'</div>';  
    }  
    add_shortcode("get-user-region", "user_region"); 

this is my shortcode inside the functions.php and i have used the shortcode inside the wordpress page

<?php echo get-user-region_callback(); ?>
<?php echo do_shortcode('[get-user-region]') ?>

I have tried both ways but both are not working no results are showing from this shortcode.

First of all, your URL to ipinfo is incorrect. If are treating the response as JSON, but the output of https://ipinfo.io/ip is HTML. You need to specify https://ipinfo.io/ip is HTML. You need to specify /json` at the end:

https://ipinfo.io/{$ip}/json

Other than that, you need to check that file_get_content is enabled on your platform and that it allows remote url loading (setting allow_url_fopen ).

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM