Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a filter by shipping method in woocommerce backend?

I need to implement a filter in the woocommerce backend, that I can use to filter the orders by the selected shipping method.

I can create a filter on custom fields and alter the query, but the problem is that woocommerce stores the shipping method in a custom table of the DB.

Any hints on how to achieve this filter?

like image 430
Lorenzo Avatar asked Dec 25 '22 03:12

Lorenzo


2 Answers

I solved adding a dropdown menu, using this hook:

add_action( 'restrict_manage_posts', 'display_shipping_dropdown' );

And then used this other hook to extend the where clause:

add_filter( 'posts_where', 'admin_shipping_filter', 10, 2 );
function admin_shipping_filter( $where, &$wp_query )
{
    global $pagenow;
    $method = $_GET['shipping_filter'];

    if ( is_admin() && $pagenow=='edit.php' && $wp_query->query_vars['post_type'] == 'shop_order' && !empty($method) ) {
        $where .= $GLOBALS['wpdb']->prepare( 'AND ID
                            IN (
                                SELECT order_id
                                FROM wp_woocommerce_order_items
                                WHERE order_item_type = "shipping"
                                AND order_item_name = "' . $method . '"
                            )' );
    }

    return $where;
}
like image 82
Lorenzo Avatar answered Dec 27 '22 18:12

Lorenzo


To complete Lorenzo's answer, here is a function you can use to generate the filter html :

function display_shipping_dropdown(){

    if (is_admin() && !empty($_GET['post_type']) && $_GET['post_type'] == 'shop_order'){

        $exp_types = array();

        $zones = WC_Shipping_Zones::get_zones();
        foreach($zones as $z) {
            foreach($z['shipping_methods'] as $method) {
                $exp_types[] = $method->title;
            }
        }

        ?>
        <select name="shipping_method">
            <option value=""><?php _e('Filter par expédition', 'woocommerce'); ?></option>
            <?php
            $current_v = isset($_GET['shipping_method']) ? $_GET['shipping_method'] : '';
            foreach ($exp_types as $label) {
                printf
                (
                    '<option value="%s"%s>%s</option>',
                    $label,
                    $label == $current_v? ' selected="selected"':'',
                    $label
                );
            }
            ?>
        </select>
        <?php
    }
}
add_action( 'restrict_manage_posts', 'display_shipping_dropdown' );
like image 40
Ben Avatar answered Dec 27 '22 16:12

Ben