Use wordpress function in PHP file

firefirehelphelp asked
php wordpress
via

I have a WordPress Child Theme and I use a php file as the template for a particular page.

I am trying to implement an API for a plugin called GeoIP Detection. Please see the PHP file I am using on my site below. The API I am trying to apply is “Redirect depending on country” located here

When I load the script, I am supposed to be redirected to https://www.google.com.sg However, it does not do so.

Thank you.

My PHP

<?php /* Template Name: GeoIPDetectionv3 */

add_action('template_redirect', 'geoip_redirect', 5);
function geoip_redirect(){
    if (is_admin())
        return;

    // This condition prevents a redirect loop:
    // Redirect only if the home page is called. Change this condition to the specific page or URL you need.
    if (!is_page(90))
        return;

    if (!function_exists('geoip_detect2_get_info_from_current_ip'))
        return;

    $userInfo = geoip_detect2_get_info_from_current_ip();
    $countryCode = $userInfo->country->isoCode;
    switch ($countryCode) {
        case 'DE':
            $url = '/germany';
            break;
        case 'US':
            $url = '/usa';
            break;
        case 'SG':
            $url = 'https://www.google.com.sg';
            break;
        default:
            $url = 'https://www.google.com.sg';
    }
    if ($url) {
        wp_redirect(get_current_blog_id(null, $url));
        exit;
    }
}


Answer
via

Use a single PHP tag, and make sure the last portion of your code is in fact inside a PHP tag. Currently it is not, so it’s parsed as plain text.

UPDATE: I’ve cleaned this up a bit for you and updated the code to reflect your revised question; i.e., following our comments below.

<?php /* Template Name: GeoIPDetectionv3 */

add_action('template_redirect', 'geoip_redirect', 5);

function geoip_redirect(){
    if ( is_admin() ) {
        return; // Not applicable.
    }
    if ( 123 !== get_current_blog_id() ) {
        return; // Not on blog ID 123.
    }
    if ( ! is_page( 90 ) ) {
        return; // Not a specific page ID on this blog.
    }
    if ( ! function_exists( 'geoip_detect2_get_info_from_current_ip' ) ) {
        return;
    }

    $userInfo    = geoip_detect2_get_info_from_current_ip();
    $countryCode = $userInfo->country->isoCode;

    switch ($countryCode) {
        case 'DE':
            $redirect_to = '/germany';
            break;
        case 'US':
            $redirect_to = '/usa';
            break;
        case 'SG':
            $redirect_to = 'https://www.google.com.sg';
            break;
        default:
            $redirect_to = 'https://www.google.com.sg';
    }
    if ( ! empty( $redirect_to ) ) {
        if ( stripos( $redirect_to, 'http' ) === 0 ) {
            wp_redirect( $redirect_to ); // Full URL.
        } else {
            wp_redirect( home_url( $redirect_to ) ); // Local /path.
        }
        exit;
    }
}
Share This
Posted in: