Skip to content

Instantly share code, notes, and snippets.

@mzdebo
Last active September 3, 2020 11:12
Show Gist options
  • Save mzdebo/664cd6f2f7869486be191f6c87849535 to your computer and use it in GitHub Desktop.
Save mzdebo/664cd6f2f7869486be191f6c87849535 to your computer and use it in GitHub Desktop.
WooCommerce Products Sort and Display by a Custom meta field
/**
* Add Publish Year sorting option to shop page / WC Product Settings - WooCommerce
*/
function thbc_publishyear_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 ( 'publishyear' == $orderby_value ) {
$sort_args['orderby'] = 'title';
$sort_args['order'] = 'asc'; //or desc
$sort_args['meta_key'] = 'publish-year';
}
return $sort_args;
}
add_filter( 'woocommerce_get_catalog_ordering_args', 'thbc_publishyear_woocommerce_shop_ordering' );
function thbc_publishyear_woocommerce_catalog_orderby( $sortby ) {
$sortby['publish-year'] = 'Sort by publish year';
return $sortby;
}
add_filter( 'woocommerce_default_catalog_orderby_options', 'thbc_publishyear_woocommerce_catalog_orderby' );
add_filter( 'woocommerce_catalog_orderby', 'thbc_publishyear_woocommerce_catalog_orderby' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment