Created
October 4, 2021 08:48
-
-
Save AchalJ/a93873b3869f13d28dfaf3d3470de8a1 to your computer and use it in GitHub Desktop.
PP Content Grid - Add WooCommerce Sorting drop-down
This file contains hidden or 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
| // Add sort by Title. | |
| add_filter( 'woocommerce_catalog_orderby', 'custom_sorting_options_wc', 99 ); | |
| add_filter( 'woocommerce_default_catalog_orderby_options', 'custom_sorting_options_wc', 99 ); | |
| function custom_sorting_options_wc( $order_by ) { | |
| $new_options = array( | |
| 'title' => __( 'Sort by Name: A to Z' ), | |
| 'title-desc' => __( 'Sort by Name: Z to A' ), | |
| ); | |
| $order_by = array_merge( $order_by, $new_options ); | |
| return $order_by; | |
| } | |
| // Add sorting drop-down before posts. | |
| add_action('pp_cg_before_posts', function ($settings, $query) { | |
| if ('cg-with-sorting' === $settings->id && function_exists('woocommerce_catalog_ordering')) { | |
| woocommerce_catalog_ordering(); | |
| } | |
| }, 10, 2); | |
| // Sorting logic. | |
| add_action('pre_get_posts', function ($query) { | |
| if ( is_admin() || ! $query->is_main_query() ) { | |
| return; | |
| } | |
| if ( isset( $_GET['orderby'] ) && ! empty( $_GET['orderby'] ) && $query->get('fl_builder_loop') ) { | |
| $orderby_value = wc_clean( (string) $_GET['orderby'] ); | |
| $orderby_value = explode( '-', $orderby_value ); | |
| $orderby = esc_attr($orderby_value[0]); | |
| $order = ! empty( $orderby_value[1] ) ? $orderby_value[1] : 'asc'; | |
| switch ( $orderby ) { | |
| case 'popularity': | |
| $query->set('meta_key', 'total_sales'); | |
| $query->set('orderby', 'meta_value_num'); | |
| $query->set('order', 'DESC'); | |
| break; | |
| case 'price': | |
| $query->set('meta_key', '_price'); | |
| $query->set('orderby', 'meta_value_num'); | |
| if ('desc' == $order) { | |
| $query->set('order', 'DESC'); | |
| } else { | |
| $query->set('order', 'ASC'); | |
| } | |
| break; | |
| case 'title': | |
| $query->set('orderby', 'title'); | |
| if ('desc' == $order) { | |
| $query->set('order', 'DESC'); | |
| } else { | |
| $query->set('order', 'ASC'); | |
| } | |
| break; | |
| case 'rating': | |
| $query->set('meta_key', '_wc_average_rating'); | |
| $query->set('orderby', 'meta_value_num'); | |
| $query->set('order', 'DESC'); | |
| break; | |
| case 'date': | |
| $query->set('orderby', 'date ID'); | |
| $query->set('order', ( 'asc' === $order ) ? 'ASC' : 'DESC'); | |
| break; | |
| default: | |
| break; | |
| } | |
| } | |
| } ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment