首页 > 解决方案 > wordpress 如何实现 php 短代码

问题描述

我试图实现可以在用户打开页面时获取用户区域但它不起作用的代码我在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"); 

这是我在functions.php中的简码,我在wordpress页面中使用了简码

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

我已经尝试了两种方法,但都没有工作,这个短代码没有显示任何结果。

标签: phpwordpress

解决方案


首先,您的网址ipinfo不正确。如果将响应视为 JSON,但最后是https://ipinfo.io/ip is HTML. You need to specify/json` 的输出:

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

除此之外,您需要检查file_get_content在您的平台上启用了它,并且它允许远程 url 加载(设置allow_url_fopen)。


推荐阅读