I have an extension to count the post views of my woocommerce products.
With this extension I have built a custom sort option.
I have used the following code in functions.php, which I have taken from several tutorials:
//Sort by views
function views_woocommerce_shop_ordering( $sort_args ) {
$orderby_value = isset( $_GET['orderby'] ) ? woocommerce_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );
if ( 'pageviews' == $orderby_value ) {
$sort_args['orderby'] = 'post_views';
$sort_args['order'] = 'desc';
}
return $sort_args;
}
add_filter( 'woocommerce_get_catalog_ordering_args', 'views_woocommerce_shop_ordering' );
function views_custom_woocommerce_catalog_orderby( $sortby ) {
$sortby['pageviews'] = 'Sort by pageviews';
return $sortby;
}
add_filter( 'woocommerce_default_catalog_orderby_options', 'views_custom_woocommerce_catalog_orderby' );
add_filter( 'woocommerce_catalog_orderby', 'views_custom_woocommerce_catalog_orderby' );
Sadly, like this it is not working. So I deleted the top part and used only this:
//PageViews Sorting
add_filter( 'woocommerce_get_catalog_ordering_args', 'custom_woocommerce_get_catalog_ordering_args' );
add_filter( 'woocommerce_default_catalog_orderby_options', 'custom_woocommerce_catalog_orderby' );
add_filter( 'woocommerce_catalog_orderby', 'custom_woocommerce_catalog_orderby',30 );
function custom_woocommerce_catalog_orderby( $sortby ) {
$sortby['post_views'] = 'Nach Beliebtheit sortiert';
return $sortby;
}
Like this it works, but when I set this custom sort option as default in the woocommerce backend, the sorting stays still default on page load, even though the new option is selected in the dropdown.
Then I have to set another option, and then back to the custom sort option - then it sorts the products correctly.
Anyone have a clue why this is happening?
Is there something wrong with my functions.php?