小编典典

在WordPress页面中插入PHP代码并发布

php

我想知道使用PHP的访问者国家/地区并将其显示在WordPress页面中。但是,当我在WordPress页面中添加PHP代码或发布时,出现错误。我们如何在WordPress
Page and Post中添加PHP代码。

  <?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'];

阅读 608

收藏
2020-05-29

共1个答案

小编典典

WordPress默认情况下不会在帖子/页面内容中执行PHP,除非它具有简码。

最快,最简单的方法是使用一个插件,使您可以运行嵌入在帖子内容中的PHP。

在没有插件的情况下,还有另外两种“快速简便”的方法可以完成此任务:

  • 将其设置为简码 (输入functions.php并使其与国家/地区名称相呼应)非常简单-参见此处:WP Codex的简码API

  • 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

2020-05-29