Hi – I would like to customize the main query in all locations to order by an ACF number field instead of by date. I don’t want any other modifications, just this. Am I on the right track with this?
function tas_album_query( $query ) {
if ( ! is_admin() && $query->is_main_query() ) {
// Not a query for an admin page.
// It's the main query for a front end page of your site.
if ( is_category() ) {
// It's the main query for a category archive.
// Let's change display order for the query for category archives.
$query->set( 'orderby', 'meta_value_num' );
$query->set( 'meta_key', 'tas_album_admin_acf_tas_album_order' );
$query->set( 'order', 'ASC' );
}
}
}
add_action( 'pre_get_posts', 'tas_album_query' );
What type of field is that? Is it a top level field or a sub field?
It was a subfield, and a number field. I changed it to be a top level field and it didn’t work there either.
I also tried this approach, but this crashed the site with a fatal error:
function tas_pre_get_posts( $query ) {
// do not modify queries in the admin
if( is_admin() ) {
return $query;
}
// only modify queries for 'post' post type
if( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'post' ) {
$query->set('orderby', 'meta_value');
$query->set('meta_key', 'tas_album_order');
$query->set('order', 'DESC');
}
// return
return $query;
}
add_action('pre_get_posts', 'tas_pre_get_posts');
I don’t see any reason why this would not work
$query->set('orderby', 'meta_value');
$query->set('meta_key', 'tas_album_order');
$query->set('order', 'DESC');
I can’t debug why you are getting the error without knowing the exact errror.
https://wordpress.org/documentation/article/debugging-in-wordpress/