温馨提示:本文翻译自stackoverflow.com,查看原文请点击:wordpress - Pop up Message when clicking Woocommerce Categories
woocommerce wordpress

wordpress - 单击Woocommerce类别时弹出消息

发布于 2020-03-31 23:56:16

我希望当没有特定邮政编码的用户尝试查看特定类别时出现弹出消息。

如果邮编不在允许的数组中,我已经达到了重定向用户的目的。

我只想声明“您无法访问此类别”并且没有任何重定向。

function my_restrict_access() {     
if ( is_product_category() ) {
    $category = get_queried_object();

    if ( $category ) {
    $category_id = $category->term_id;

    $allowed_category_id = array(3078, 3385);

    if ( in_array($category_id, $allowed_category_id) ) {
    if ( !is_user_logged_in() ) {
        wp_redirect( '/' );
        exit;
        } else {
        global $woocommerce;
        $customer = new WC_Customer();
        $customer_postcode = $woocommerce->customer->get_billing_postcode();

        // uncomment line below for debug purposes, this will show you the postcode on the current page
        //echo $customer_postcode;

        $allowed_post_code = array(3610, 3626, 3650);

        if ( !in_array($customer_postcode, $allowed_post_code) ) {
        wp_redirect( '/' );
        exit;
        }
    }
    }
    }
}
}
add_action( 'template_redirect', 'my_restrict_access');

查看更多

提问者
Jürgen Walter Hof
被浏览
93
Sajjad Hossain Sagor 2020-01-31 20:17

您最好使用wp过滤器the_content来更改前台内容...

add_action( 'the_content', 'restrict_user_to_certain_shop_category' );

function restrict_user_to_certain_shop_category( $content ){

   global $woocommerce;

   // list of all allowed woo product categories
   $allowed_categories = array( 3078, 3385 );

   // allowed user whose postcodes are following
   $allowed_post_codes = array( 3610, 3626, 3650 );

   // check if current viweing page is product archive page
   if ( is_product_category() ) {

      $current_category = get_queried_object();

      // extract archive category id
      $current_category_id = $current_category->term_id;

      // check if current category is in allowed array list
      if ( in_array( $current_category_id, $allowed_categories ) ) {

          // check if user is not logged in
          if ( ! is_user_logged_in() ) {

              // message to show when user is not logged in and viewing allowed product category
              $content = 'You cannot access this category';
          }

          // user is logged in and viewing allowed product category
          else {

              $customer = new WC_Customer();

              $customer_postcode = $woocommerce->customer->get_billing_postcode();

              // check if user is from allowed postarea
              if ( !in_array( $customer_postcode, $allowed_post_codes ) ) {

                   // message to show when user is logged in and viewing allowed product category + from allowed postarea
                  $content = 'You cannot access this category';
              }
           }
        }
      }

   return $content;
}