首页 文章

如何在woocommerce后端通过送货方式实现过滤器?

提问于
浏览
1

我需要在woocommerce后端实现一个过滤器,我可以使用所选的送货方法来过滤订单 .

我可以在自定义字段上创建过滤器并更改查询,但问题是woocommerce将发货方法存储在数据库的自定义表中 .

有关如何实现此过滤器的任何提示?

2 回答

  • 1

    我解决了添加下拉菜单,使用此钩子:

    add_action( 'restrict_manage_posts', 'display_shipping_dropdown' );
    

    然后使用这个其他钩子来扩展where子句:

    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;
    }
    
  • 0

    要完成Lorenzo的答案,这里有一个可用于生成过滤器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' );
    

相关问题