WooCommerce支援 HPOS的訂單篩選功能Function

ChatGPT問很久總算成功了,可在啟用HPOS ( High-Performance Order Storage ) 後的訂單管理頁,額外增加客制的篩選功能

// 1. 在訂單列表上方新增篩選欄位(日期區間)
add_action('woocommerce_order_list_table_restrict_manage_orders', function($order_type, $which) {
    if ($which === 'top') {
        ?>
        <label for="from_date">出貨備註起始日期:</label>
        <input type="date" id="from_date" name="from_date" 
               value="<?php echo isset($_GET['from_date']) ? esc_attr($_GET['from_date']) : ''; ?>" />

        <label for="to_date">出貨備註結束日期:</label>
        <input type="date" id="to_date" name="to_date" 
               value="<?php echo isset($_GET['to_date']) ? esc_attr($_GET['to_date']) : ''; ?>" />
        <?php
    }
}, 10, 2);

// 2. 依照 shipping_date_note 篩選訂單(支援 HPOS)
add_filter('woocommerce_order_list_table_prepare_items_query_args', function($args) {
    $from_date = isset($_GET['from_date']) ? sanitize_text_field($_GET['from_date']) : '';
    $to_date   = isset($_GET['to_date']) ? sanitize_text_field($_GET['to_date']) : '';

    if ($from_date || $to_date) {
        $meta_query = $args['meta_query'] ?? [];
        if ($from_date) {
            $meta_query[] = [
                'key'     => 'shippind_date_note',  // 注意這裡的拼字!
                'value'   => $from_date,
                'compare' => '>=',
                'type'    => 'DATE',
            ];
        }
        if ($to_date) {
            $meta_query[] = [
                'key'     => 'shippind_date_note',
                'value'   => $to_date,
                'compare' => '<=',
                'type'    => 'DATE',
            ];
        }
        $args['meta_query'] = $meta_query;
    }
    return $args;
});

可以使用訂單編號(置換 id 12345),然後再把你要篩選的對應欄位給ChatGPT調整

SELECT * FROM wp_postmeta WHERE post_id = 12345;

HPOS 的效能是真的有淬出來,我自己的MAC主機有架一台,啟用後搜尋 999 筆,3秒內能出現資訊

瀏覽次數:35