最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Add search form to WooCommerce My Account > Orders page to query specific order data - Stack Overflow

programmeradmin4浏览0评论

Having to go "back to the drawing board" as my previous question, although worked, it only worked because of the ['post__in'] being the order ID.

Objective: add a frontend search form for customer to search orders their own orders on the My Account > Orders page.

This shop has a couple of wholesale accounts that drop ship ordered products. They have a lot of order history in their accounts, and ideally need to be able to search by order number and shipping details (shipping first name, shipping last name, shipping address, etc).

Disclaimer: This shop has been fully converted to HPOS and the legacy data deleted and compatibility mode turned off.

I feel like I'm close, but the following code generates no results no matter what is queried in the form, messaging: "No order has been made yet."

function add_search_to_orders() {
    $allowed_roles = array('administrator', 'shop_manager');
    $user = wp_get_current_user();
    $user_roles = (array) $user->roles;

    if (array_intersect($allowed_roles, $user_roles)) {
        $show_clear_link = isset($_GET['search_orders']) && !empty($_GET['search_orders']);
        echo '<form method="get" id="orders-search-form">
                <input type="text" name="search_orders" placeholder="Search..." value="' . (isset($_GET['search_orders']) ? esc_attr($_GET['search_orders']) : '') . '" />
                <button type="submit">Search</button>';
        if ($show_clear_link) {
            echo '<a href="' . esc_url(remove_query_arg('search_orders')) . '">Reset Search</a>';
        }
        echo '</form>';
    }
}

add_action('woocommerce_before_account_orders', 'add_search_to_orders');

add_filter('woocommerce_my_account_my_orders_query', 'search_orders_query', 10, 1);
function search_orders_query($args) {
    if (isset($_GET['search_orders'])) {
        $search_term = sanitize_text_field($_GET['search_orders']);
        
        $args['meta_query'][] = array(
            'key'     => 'order_number',
            'value'   => $search_term,
            'compare' => 'LIKE'
        );

        $args['meta_query'][] = array(
            'relation' => 'OR',
            array(
                'key'     => 'shipping_first_name',
                'value'   => $search_term,
                'compare' => 'LIKE'
            ),
            array(
                'key'     => 'shipping_last_name',
                'value'   => $search_term,
                'compare' => 'LIKE'
            )
        );

        $args['meta_query']['relation'] = 'OR';
    }
    return $args;
}

I've added in some user role checks and also a reset search link for good measure.

How can I get this to show actual results?

发布评论

评论列表(0)

  1. 暂无评论