php - 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]') ?>
我已经尝试了两种方法,但都没有工作,这个短代码没有显示任何结果。
解决方案
首先,您的网址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
)。
推荐阅读
- reactjs - 我可以在一个 monorepo 中有多个 babel.config.js 吗?
- excel - 宏/UDF 从单元格中提取多次出现的文本 URL
- javascript - 在 html 、 js 、 php 中的随机问题中添加图像
- cassandra - Cassandra 维护插入和更新时间戳
- ios - 防止触摸从 UIControl 传递到 ParentView
- c - Linked List 功能解释,结构体指针的订阅
- asp.net - 如何使用 Angular 6 获取操作系统用户名
- fiware-orion - FIWARE Orion:返回订阅 ID
- javascript - 将 Vue 路由器与经典 Symfony 应用程序路由混合
- python - 如何在 Python 的嵌套列表中插入元素?