Search and Sort WooCommerce Shop Orders by Company Name
Original Prompt: On the Orders table, add a new filter action (search input field) to search by Company Name. The name is stored in a custom meta field (company_name) in single orders.
add_action( 'restrict_manage_posts', 'cwpai_woo_filter_orders_by_company_name' );
function cwpai_woo_filter_orders_by_company_name() {
global $typenow;
if ( 'shop_order' === $typenow ) {
?>
<input type="text" name="company_name" id="company_name" placeholder="<?php esc_attr_e( 'Filter by Company Name', 'cwpai' ); ?>" value="<?php echo esc_attr( filter_input( INPUT_GET, 'company_name' ) ); ?>" />
<?php
}
}
add_filter( 'parse_query', 'cwpai_woo_filter_orders_by_company_name_query' );
function cwpai_woo_filter_orders_by_company_name_query( $query ) {
global $pagenow;
$qv = &$query->query_vars;
if ( 'edit.php' === $pagenow && isset( $qv['post_type'] ) && 'shop_order' === $qv['post_type'] && isset( $_GET['company_name'] ) && ! empty( $_GET['company_name'] ) ) {
$qv['meta_query'] = array(
array(
'key' => 'company_name',
'value' => sanitize_text_field( $_GET['company_name'] ),
'compare' => 'LIKE',
),
);
}
}
Snippet Explanation
This code is written in PHP.
1. The first step is to add an action to restrict posts to the 'shop_order' post type. This will add a search field to the 'shop_order' post type list page in the WordPress admin.
2. The second step is to define a function that will add the search field to the 'shop_order' post type list page in the WordPress admin.
3. The third step is to add a filter to the query to search for orders by company name.
4. The fourth step is to define a function that will filter the query based on the company name.
5. The final step is to apply the query variables to the query and search for orders by company name.
The purpose of this code is to add a search field to the 'shop_order' post type list page in the WordPress admin, allowing users to filter orders by company name.
To install this code on WordPress, you can add it to the functions.php file of your theme, or you can use a snippet management plugin. Once installed, you will be able to filter orders by company name on the 'shop_order' post type list page in the WordPress admin.