WooCommerce restrict shipping to states based on c

2019-06-11 02:46发布

I am trying to come up with a solution to limit the stated that a product category can be shipped to. Here is what I have come up with so far.

    function get_prod_cat () {
    global $woocommerce;
    $specialfeecat = 34; // category id for the special fee
    $items = $woocommerce->cart->get_cart();
    foreach ($items as $item ) {
      $product = $item['data'];
      $terms = get_the_terms( $product->id, 'product_cat' );
        if ( $terms && ! is_wp_error( $terms ) ) :
            foreach ( $terms as $term ) {
                $catid = $term->term_id;
                if($specialfeecat == $catid ) {
                    $GLOBALS['cat_id'] = $catid;
                }
            return $cat_id;
            }
        endif;
    }  
}
if ($cat_id == 34) {
add_filter( 'woocommerce_states', 'wc_sell_only_states' );
}
function wc_sell_only_states() {    
        $states['US'] = array(
        'AK' => __( 'Arkansas', 'woocommerce' ),
        'DC' => __( 'Washington DC', 'woocommerce' ),
        'IL' => __( 'Illinois', 'woocommerce' ),
        'KY' => __( 'Kentucky', 'woocommerce' ),
        'MN' => __( 'Minnesota', 'woocommerce' ),
        'NM' => __( 'New Mexico', 'woocommerce' ),
        );
        return $states;
}

I am trying to get the variable $cat_id from the first function out of it so that I can use it for the condition to limit states. Thanks in advance.

1条回答
兄弟一词,经得起流年.
2楼-- · 2019-06-11 03:32

Call add_filter( 'woocommerce_states', 'wc_sell_only_states' ); as you have done. Inside function 'wc_sell_only_states($states)' apply your logic, which you were doing inside 'get_prod_cat'. If category matched then change states

$states['US'] = array(
        'AK' => __( 'Arkansas', 'woocommerce' ),
        'DC' => __( 'Washington DC', 'woocommerce' ),
        'IL' => __( 'Illinois', 'woocommerce' ),
        'KY' => __( 'Kentucky', 'woocommerce' ),
        'MN' => __( 'Minnesota', 'woocommerce' ),
        'NM' => __( 'New Mexico', 'woocommerce' ),
        );

Else return states as it was.

查看更多
登录 后发表回答