Created
September 9, 2022 15:57
-
-
Save passatgt/26df1537c88ba06184105594c0762a0a to your computer and use it in GitHub Desktop.
WooCommerce product search for My Account / Orders
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Create search bar on the top of the my account / orders page | |
add_action('woocommerce_before_account_orders', function(){ | |
?> | |
<form method="get"> | |
<input type="text" name="keyword" placeholder="Keresés" value="<?php echo esc_attr($_GET['keyword']); ?>"> | |
<input type="submit" value="Keresés" /> | |
</form> | |
<?php | |
$customer_orders = false; | |
}); | |
//Overwrite the woocommerce_account_orders function to load a different query for custom search | |
function woocommerce_account_orders( $current_page ) { | |
$current_page = empty( $current_page ) ? 1 : absint( $current_page ); | |
//Check if a keyword is set | |
if(isset($_GET['keyword'])) { | |
//Find order ids with a given keyword(this will search for product names) | |
$order_ids = wc_order_search( wc_clean( wp_unslash( $_GET['keyword'] ) ) ); | |
$order_statuses = wc_get_order_statuses(); | |
$customer_orders = false; | |
//If we have some search results | |
if ( ! empty( $order_ids ) ) { | |
//Create a new wp_query | |
$args = array( | |
'post__in' => $order_ids, | |
'meta_query' => array( | |
array( | |
'key' => '_customer_user', | |
'value' => get_current_user_id(), | |
'compare' => '=', | |
), | |
), | |
'post_status' => array_keys( $order_statuses ), | |
'post_type' => 'shop_order' | |
); | |
$the_query = new WP_Query( $args ); | |
$the_query->query_vars['shop_order_search'] = true; | |
//Customize query, so the orders.php template can use it | |
$customer_orders = $the_query; | |
$customer_orders->orders = array(); | |
//Collect found order ids | |
if ( $the_query->have_posts() ) { | |
while ( $the_query->have_posts() ) { | |
$the_query->the_post(); | |
$customer_orders->orders[] = get_the_ID(); | |
} | |
} | |
} | |
wc_get_template( | |
'myaccount/orders.php', | |
array( | |
'current_page' => absint( $current_page ), | |
'customer_orders' => $customer_orders, | |
'has_orders' => 0 < $customer_orders->found_posts, | |
) | |
); | |
//Return original stuff if keyword is not set | |
} else { | |
$customer_orders = wc_get_orders( | |
apply_filters( | |
'woocommerce_my_account_my_orders_query', | |
array( | |
'customer' => get_current_user_id(), | |
'page' => $current_page, | |
'paginate' => true, | |
) | |
) | |
); | |
wc_get_template( | |
'myaccount/orders.php', | |
array( | |
'current_page' => absint( $current_page ), | |
'customer_orders' => $customer_orders, | |
'has_orders' => 0 < $customer_orders->total, | |
) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment