Reputation: 739
I am trying to change the default sorting order in woocommerce admin screen.
I am trying the following code to sort the product page by product name by default.
/* Sort posts in wp_list_table by column in ascending or descending order. */
function custom_post_order($query){
/*
Set post types.
_builtin => true returns WordPress default post types.
_builtin => false returns custom registered post types.
*/
$post_types = get_post_types(array('_builtin' => false), 'names');
/* The current post type. */
$post_type = $query->get('post_type');
/* Check post types. */
if(in_array($post_type, $post_types) && $post_type == 'product'){
/* Post Column: e.g. title */
if($query->get('orderby') == ''){
$query->set('orderby', 'title');
}
/* Post Order: ASC / DESC */
if($query->get('order') == ''){
$query->set('order', 'ASC');
}
}
}
if(is_admin()){
add_action('pre_get_posts', 'custom_post_order');
}
But it does not seems to be working. Can anyone please point where I am going wrong Or does woocommerce handles product columns differently.
Upvotes: 0
Views: 3805
Reputation: 26319
I would target parse_query
instead. This seems to be working for me:
/* Sort products in wp_list_table by column in ascending or descending order. */
function sp_41964737_custom_product_order( $query ){
global $typenow;
if( is_admin() && $query->is_main_query() && $typenow == 'product' ){
/* Post Column: e.g. title */
if($query->get('orderby') == ''){
$query->set('orderby', 'title');
}
/* Post Order: ASC / DESC */
if($query->get('order') == ''){
$query->set('order', 'ASC');
}
}
}
add_action( 'parse_query', 'sp_41964737_custom_product_order' );
Results in:
Upvotes: 2