Filter WooCommerce orders by payment method

In this tutorial you will learn how to create a filter in the WooCommerce order list.

The result will be a filter in the order list in WordPress Admin > WooCommerce > Orders:

Filter WooCommerce orders by payment method

The first step is to create a dropdown with the payment methods, which we will do with the function filter_orders_by_payment_method:

<?php
function filter_orders_by_payment_method(): void
{
	global $typenow;

	if ($typenow == 'shop_order') {

		$gateways = WC()->payment_gateways->payment_gateways();
		?>
        <select name="_order_payment_method">
            <option value="">All Payment Methods</option>
			<?php foreach ($gateways as $id => $gateway) : ?>
                <?php $payment_method = $_GET['_order_payment_method'] ?? ''; ?>
                <option value="<?php echo esc_attr($id); ?>" <?php selected($id, $payment_method); ?>>
					<?php echo esc_html($gateway->get_method_title()); ?>
                </option>
			<?php endforeach; ?>
        </select>
		<?php
	}
}

Let’s take a look at what’s going in the code. In line 6 we check if we are on the WooCommerce order page. Then we get all the payment methods in line 8 and this list includes all inactive methods. Finally, we loop over the list and print all the options containing the payment methods.

The next step is to modify the query of the order page, which we will do with the function filter_orders_by_payment_method_query:

function filter_orders_by_payment_method_query(array $vars): array
{
	global $typenow;

	if ('shop_order' === $typenow && isset($_GET['_order_payment_method']) && !empty($_GET['_order_payment_method'])) {
		$vars['meta_key'] = '_payment_method';
		$vars['meta_value'] = wc_clean($_GET['_order_payment_method']);
	}

	return $vars;
}

In line 5 of the filter_orders_by_payment_method_query function we check if we are on the order page and if the _order_payment_method parameter is set. If that is the case, we set the meta_key and meta_value.

If you are using Ray for WordPress you can dump the value of $vars by using ray($vars); and you will get something like this:

Ray dump

As you can see meta_key and meta_value has been added to the query

Finally, we need to register the filter_orders_by_payment_method action and filter_orders_by_payment_method_query filter but we don’t need to add the code on the frontend so we start by checking if we are in admin i line 1:

if (is_admin()) {
	add_action('restrict_manage_posts', 'filter_orders_by_payment_method');
	add_filter('request', 'filter_orders_by_payment_method_query');
}

That’s it! Let me know if you have any questions in the comments.

Posted in #

Torben Lundsgaard Avatar

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *