Skip to main content

[WordPress] Thêm bộ lọc tình trạng đơn hàng trong trang Tài Khoản

Thêm tính năng hữu ích cho khách hàng là tìm kiếm lọc các đơn đặt hàng “Đang chờ xử lý” hoặc các đơn đặt hàng “Đã hoàn thành” nhanh chóng

Image
Thêm bộ lọc tình trạng đơn hàng trong trang Tài Khoản

Để làm có thể tham khảo snippet code này

Bước 1 - Hiển thị danh sách bộ lọc

 
add_action( 'woocommerce_before_account_orders', 'bbloomer_my_account_orders_filters' );

function bbloomer_my_account_orders_filters() {
  echo '<p>Filter by: ';
  $customer_orders = 0;
  foreach ( wc_get_order_statuses() as $slug => $name ) {
     $status_orders = count( wc_get_orders( [ 'status' => $slug, 'customer' => get_current_user_id(), 'limit' => -1 ] ) );
     if ( $status_orders > 0 ) {
        if ( isset( $_GET['status'] ) && ! empty( $_GET['status'] ) && $_GET['status'] == $slug ) { 
           echo '<b>' . $name . ' (' . $status_orders . ')</b><span class="delimit"> - </span>';
        } else echo '<a href="' . add_query_arg( 'status', $slug, wc_get_endpoint_url( 'orders' ) ) . '">' . $name . ' (' . $status_orders . ')</a><span class="delimit"> - </span>';
     }
     $customer_orders += $status_orders;
  }
  if ( isset( $_GET['status'] ) && ! empty( $_GET['status'] ) ) {
     echo '<a href="' . remove_query_arg( 'status' ) . '">All statuses (' . $customer_orders . ')</a>';
  } else echo '<b>All statuses (' . $customer_orders . ')</b>';
  echo '</p>';
}

Bước 2 - Nhận tham số bộ lọc qua params

add_filter( 'woocommerce_my_account_my_orders_query', 'bbloomer_my_account_orders_filter_by_status' );

function bbloomer_my_account_orders_filter_by_status( $args ) {
  if ( isset( $_GET['status'] ) && ! empty( $_GET['status'] ) ) {
     $args['status'] = array( $_GET['status'] );
  }
  return $args;
}

Bước 3 - Thay đổi url của filter

add_filter( 'woocommerce_get_endpoint_url', 'bbloomer_my_account_orders_filter_by_status_pagination', 9999, 4 );
         
function bbloomer_my_account_orders_filter_by_status_pagination( $url, $endpoint, $value, $permalink ) {
  if ( 'orders' == $endpoint && isset( $_GET['status'] ) && ! empty( $_GET['status'] ) ) {
     return add_query_arg( 'status', $_GET['status'], $url );
  }
  return $url;
}

Nguồn: businessbloomer.com