I see that it is possible to add your custom field for sorting products in WooCommerce (e.g. this question) Copying from the example:
add_filter( 'woocommerce_get_catalog_ordering_args', 'enable_catalog_ordering_by_modified_date' );
function enable_catalog_ordering_by_modified_date( $args ) {
if ( isset( $_GET['orderby'] ) ) {
if ( 'modified_date' == $_GET['orderby'] ) {
return array(
'orderby' => 'modified', //This is the custom field to be sorted by, and what I am asking for
'order' => 'DESC',
);
}
}
return $args;
}
Is there a list of all fields that I can use for sorting?
P.S. Thanks for the comment, but what I need is not sorting normal posts in WordPress, but the products in WooCommerce.
3
Answers
These are the default list of orderby options available
( id, title, relevance, rand, date, price, popularity, rating)
. The case of the switch case may be what you are looking for.The above code is from
woocommerce/includes/class-wc-query.php
line 586…You need to know what is inside of an product object. You can sort your products by any of this product data.
Here is a list I found where you can access all the data inside of a product object.
(source: https://wpdavies.dev/how-to-get-all-product-info-in-woocommerce/)
With this you can see under "other product data", that there is a
date_modified
you can order your products by.It is not directly a list of all fields you can sort by. But it indirectly shows you which fields are available inside a product and what the fields are called. With the name, you are able to access them.
Custom meta:
Unfortunatelly there is no data saved for "published_date". But you could create a custom field for your product post type and save the date inside product. Via the meta key you can than access the data of the product and sort your products by your custom meta data.
If the point of the question is whether there is a list that returns all the fields that can be used for sorting, the short answer is no.
The
woocommerce_get_catalog_ordering_args
filter allows you to add your own ordering args, but there is no list that would store these fields. This filter is used to overwrite args, not to store it as an array.Within the
get_catalog_ordering_args()
function, someorderby
defaults are statically specified:id
,menu_order
,title
,relevance
,rand
,date
,price
,popularity
,rating
.But there is no way to tell what values have been added using a filter by WordPress plugins.
Possible solution:
There is a
woocommerce_catalog_orderby
filter that stores sorting options as an array.This is used to display sorting options in the view. So you can assume that WordPress plugins will add options to this as well.
You can use
$catalog_orderby_options
in which the sorting options are stored, if you only need the orderby fields, use thearray_keys()
function.Note: you must specify the default value in
apply_filters()
, because WooCommerce added these statically, not usingadd_filter()
. So you have to add it statically too.