phpwordpresswoocommerce

dont allow PO BOX shipping woocommerce not working


add_action('woocommerce_after_checkout_validation', 'deny_pobox_postcode');

function deny_pobox_postcode( $posted ) {
 global $woocommerce;

 $address  = ( isset( $posted['shipping_address_1'] ) ) ?          $posted['shipping_address_1'] : $posted['billing_address_1'];
 $postcode = ( isset( $posted['shipping_postcode'] ) ) ?    $posted['shipping_postcode'] : $posted['billing_postcode'];

$replace  = array(" ", ".", ",");
$address  = strtolower( str_replace( $replace, '', $address ) );
$postcode = strtolower( str_replace( $replace, '', $postcode ) );

if ( strstr( $address, 'pobox' ) || strstr( $postcode, 'pobox' ) ) {
  $woocommerce->add_error( "Sorry, we don't ship to PO BOX addresses." );
 }
}

i am getting:

fatal error :call to undefined add_error

when i am pasting on my function .php


Solution

  •  add_action('woocommerce_after_checkout_validation', 'deny_pobox_postcode');
    
    function deny_pobox_postcode( $posted ) {
     global $woocommerce;
    
      $address  = ( isset( $posted['shipping_address_1'] ) ) ?     
     $posted['shipping_address_1'] : $posted['billing_address_1'];
    
     $postcode = ( isset( $posted['shipping_postcode'] ) ) ?  
     $posted['shipping_postcode'] : $posted['billing_postcode'];
    
     $replace  = array(" ", ".", ",");
     $address  = strtolower( str_replace( $replace, '', $address ) );
     $postcode = strtolower( str_replace( $replace, '', $postcode ) );
    
     if ( strstr( $address, 'pobox' ) || strstr( $postcode, 'pobox' ) ) {
       $notice = sprintf( __( '%1$sSorry, we dont ship to PO BOX addresses..' , 'error' ) , '<strong>' , '</strong>' );
    
            if ( version_compare( WC_VERSION, '2.3', '<' ) ) {
                $woocommerce->add_error( $notice );
            } else {
                wc_add_notice( $notice, 'error' );
            }
      }
    }