Blog

  • Useful WooCommerce Snippets

    Posted at 13 Aug, 2018 in Solutions

    Here are some handy WooCommerce code snippets to control the payment and shipping methods.

    Remove Payment Gateways:

    Paste the following code in your theme’s ‘functions.php’. This will remove the specified payment methods when specific shipping methods available.


    /** function to alter payment gateways **/
    function alter_payment_methods($available_gateways){
    global $woocommerce;
    $chosen_titles = array();
    $available_methods = $woocommerce->shipping->get_packages();
    $chosen_rates = ( isset( $woocommerce->session ) ) ? $woocommerce->session->get( 'chosen_shipping_methods' ) : array();
    foreach ($available_methods as $method)
    foreach ($chosen_rates as $chosen) {
    if( isset( $method['rates'][$chosen] ) ) $chosen_titles[] = $method['rates'][ $chosen ]->label;
    }
    if( in_array( 'Collect in store', $chosen_titles ) ) { //shipping method titles
    unset($available_gateways['paypal']); //payment gateway names
    }
    return $available_gateways;
    }
    add_action('woocommerce_available_payment_gateways', 'alter_payment_methods');

    Feel free to change the shipping method labels and payment gateway names above.

    Remove Shipping Methods:

    Paste the following code in your theme’s ‘functions.php’. This will remove the specified shipping methods when specific shipping method available (for example, you can remove all other shipping methods if free shipping method available).


    /** function to alter shipping methods **/
    function alter_shipping_methods($rates){
    foreach ( $rates as $rate_id => $rate ) {
    if ( stristr($rate->method_id,'free_shipping') ) {
    unset( $rates['flat_rate:4'] ); //shipping method name:id
    }
    }
    }
    add_filter( 'woocommerce_package_rates', 'alter_shipping_methods', 10, 2 );

    Feel free to change the shipping method names above.

Categories

Categories

Archives

Archives