Custom Redirection based on Geolocation for specific products in WooCommerce

筅森魡賤 提交于 2020-01-03 01:47:25

问题


I need to re-direct customers from Germany to a custom page if they try to access a product page and I've started to put something together, but I don't know how to finish it.

Here's what I got:

add_action( 'do not know which hook to use', 'geo_origin_redirect' );
function geo_origin_redirect() {
        $location = WC_Geolocation::geolocate_ip();
        $country = $location['country'];

        $product_ids = array( 10, 20, 30 );
        $product_categories = array( 'makeup' );
        $redirection = false;

        // what to do here to make it check the product?
        if( in_array( $???->get_product_id(), $product_ids ) || has_term( $product_categories, 'product_cat', $???->get_product_id() ) ) {
        $redirection = true;
        break;
        }
    }
        if( $redirection && $country === 'Germany' ){
        wp_redirect( home_url( '/your-page/' ) );
        exit;
    }
}

Any help is appreciated.


回答1:


You can use template_redirect dedicated WordPress hook, this way:

add_action( 'do not know which hook to use', 'geo_origin_redirect' );
function geo_origin_redirect() {
    // Only on single product pages and "Germany" geolocated country
    if ( ! ( is_product() && WC_Geolocation::geolocate_ip()['country'] === 'GE' ) )
        return;

    $product_ids        = array( 10, 20, 30 );
    $product_categories = array( 'makeup' );
    $redirection_url    = home_url( '/your-page/' );

    if( in_array( get_the_id(), $product_ids ) || has_term( $product_categories, 'product_cat' ) ) {
        wp_redirect( $redirection_url );
        exit;
    }
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.



来源:https://stackoverflow.com/questions/57466134/custom-redirection-based-on-geolocation-for-specific-products-in-woocommerce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!