WordPress tips & tricks

Alter WooCommerce payment methods based on shipping

A few days ago we struggled with a WooCommerce webshop which had a specific payment method which was only valid for pick-up the products in the store. It took a while before we figured out how to make this work. At first we had a javascript / jQuery approach which did the job, but wasn’t that flexible and could lead to conflicts on different themes etc.

Thanks to a lot of Googling (we love that word) we found the solution which we’re going to share with you! The code below works for WooCommerce 2.1 and above.

How to change allowed payment based on selected shipping method

It’s easy to change which payment methods are allowed if you know how WooCommerce handles payment methods and shipping methods. You can use the code below in your (child) theme functions.php or in a custom plugin. In below code we remove the “Cheque” payment method (WC_Gateway_Cheque) when “Local Pick up” is NOT selected.


/**
* Change payment methods based on shipping methods
**/
function wpf_alter_payment_method($list){

// Get all available shipping methods
$chosen_rates = ( isset( WC()->session ) ) ? WC()->session->get( 'chosen_shipping_methods' ) : array();

// Check if the specific shipping_method ID is chosen.
if(!in_array( 'local_pickup', $chosen_rates ) ) { // Change "local_pickup".

// Remove specific payment method from list. In this case "WC_Gateway_Cheque"
$array_diff = array('WC_Gateway_Cheque'); // Change "WC_Gateway_Cheque"
$list = array_diff( $list, $array_diff );
}
return $list;
}
add_action('woocommerce_payment_gateways', 'wpf_alter_payment_method');

If you’ve a question about how to change the payment method based on selected shipping method you can add your comment below!

How to install plugins on localhost

We like to develop our WordPress sites on a localhost (for example with XAMPP). Working locally is great: it’s a lot faster, we can test on different configurations, we can use versioning software and there are less risks. We only noticed a lot of problems with installing plugins from within the WP Plugin page.

Read more

3 .htaccess tricks to make your WordPress site more secure

Many WordPress users know the .htaccess file from fixing permalinks or make 301 redirects from old to new pages. But you can do more with your .htaccess file! With the .htacess file you can improve your site’s performance and security. In this article we’ll give you some nice .htaccess tricks to make WordPress more secure.

Read more