在 WordPress 页面中插入 PHP 代码并发布
我想知道使用 PHP 的访问者国家并将其显示在 WordPress 页面上.但是当我将 PHP 代码添加到 WordPress 页面或发布时,它给了我一个错误.
I want to know the visitor country using PHP and display it in on a WordPress Page. But when I add PHP code to a WordPress page or post it gives me an error.
我们如何在 WordPress 页面和帖子中添加 PHP 代码?
How can we add PHP code on WordPress pages and posts?
<?PHP
try
{
function visitor_country()
{
$client = @$_SERVER['HTTP_CLIENT_IP'];
$forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
$remote = $_SERVER['REMOTE_ADDR'];
$result = "Unknown";
if(filter_var($client, FILTER_VALIDATE_IP))
{
$ip = $client;
}
elseif(filter_var($forward, FILTER_VALIDATE_IP))
{
$ip = $forward;
}
else
{
$ip = $remote;
}
$ip_data = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=" . $ip));
if($ip_data && $ip_data->geoplugin_countryName != null)
{
$result = array('ip' => $ip,
'continentCode' => $ip_data->geoplugin_continentCode,
'countryCode' => $ip_data->geoplugin_countryCode,
'countryName' => $ip_data->geoplugin_countryName,
);
}
return $result;
}
$visitor_details = visitor_country(); // Output Country name [Ex: United States]
$country = $visitor_details['countryName'];
WordPress 默认不会在帖子/页面内容中执行 PHP,除非它有短代码.
WordPress does not execute PHP in post/page content by default unless it has a shortcode.
执行此操作的最快和最简单的方法是使用一个插件,该插件允许您运行嵌入在帖子内容中的 PHP.
The quickest and easiest way to do this is to use a plugin that allows you to run PHP embedded in post content.
还有另外两种快速而简单"的方法可以在没有插件的情况下完成它:
There are two other "quick and easy" ways to accomplish it without a plugin:
将其设为短代码(将其放入
functions.php
并使其与国家/地区名称相呼应),这非常简单 - 请参阅此处:WP Codex 的 Shortcode API
Make it a shortcode (put it in
functions.php
and have it echo the country name) which is very easy - see here: Shortcode API at WP Codex
将其放入模板文件 - 根据您的默认页面模板为该页面创建自定义模板,并将 PHP 添加到模板文件中而不是帖子内容中:自定义页面模板
Put it in a template file - make a custom template for that page based on your default page template and add the PHP into the template file rather than the post content: Custom Page Templates