WordPress.org

Ready to get started?Download WordPress

Forums

WooCommerce - excelling eCommerce
[resolved] Do Not Allo PO Boxes (4 posts)

  1. imfromio
    Member
    Posted 1 year ago #

    I cannot ship products to PO Boxes so I found this snippet to do that:

    add_action('woocommerce_after_checkout_validation', 'deny_pobox_postcode');
    
    function deny_pobox_postcode( $posted ) {
      global $woocommerce;
    
      $postcode = ( isset( $this->posted['shipping_postcode'] ) ) ? $this->posted['shipping_postcode'] : $this->posted['billing_postcode'];
    
      $postcode = strtolower(str_replace( ' ', '', $postcode ));
    
      if ( strstr( $postcode, 'pobox' ) ) {
        $woocommerce->add_error( "Sorry, we don't ship to PO BOX addresses." );
      }
    }

    This code comes from here: https://gist.github.com/2282666

    The problem is, when I add this snippet to my theme's function.php file, I get this fatal error: Using $this when not in object context in...

    What am I doing wrong?

    http://wordpress.org/extend/plugins/woocommerce/

  2. samueljeden
    Member
    Posted 1 year ago #

    The code is written wrong :(

    add_action('woocommerce_after_checkout_validation', 'deny_pobox_postcode');
    
    function deny_pobox_postcode( $posted ) {
      global $woocommerce;
    
      $postcode = ( isset( $posted['shipping_postcode'] ) ) ? $posted['shipping_postcode'] : $posted['billing_postcode'];
    
      $postcode = strtolower(str_replace( ' ', '', $postcode ));
    
      if ( strstr( $postcode, 'pobox' ) ) {
        $woocommerce->add_error( "Sorry, we don't ship to PO BOX addresses." );
      }
    }

    Dont need to define it as $this->posted as we are passing $posted through already :).

    The code above works.. it is not an ideal solution though.

    http://cl.ly/image/2y0J0J3z2l41

  3. imfromio
    Member
    Posted 1 year ago #

    Thanks! That code works. But I realized that it is checking the Post Code instead of the street address where most customers would put the PO Box, so I edited it as so:
    add_action('woocommerce_after_checkout_validation', 'deny_pobox_postcode');

    function deny_pobox_postcode( $posted ) {
     global $woocommerce;
    
     $postcode = ( isset( $posted['shipping_address_1'] ) ) ? $posted['shipping_address_1'] : $posted['billing_address_1'];
    
     $postcode = strtolower(str_replace( ' ', '', $postcode ));
    
     if ( strstr( $postcode, 'pobox' ) ) {
       $woocommerce->add_error( "Sorry, we cannot ship to PO BOX addresses." );
     }
    }

    And it's working fine now.

  4. kjoy
    Member
    Posted 7 months ago #

    I would like to use this code as I can't ship to PO Boxes either, but when I place it in my functions.php file it still allows me to enter a PO Box as my shipping address. Any insight?

Topic Closed

This topic has been closed to new replies.

About this Plugin

About this Topic