Hi, I'm trying to change the sort order of a custom post type taxonomy archive. I've read your documentation and have copied the code.
It works ,but it changes the sort order of all posts on the site, instead of just the specific custom taxonomy.
This is the code I have:
//Customise Speakers taxonomy archive display
add_action( 'pre_get_posts', 'customise_speakers_taxonomy_archive_display' );
function customise_speakers_taxonomy_archive_display ( $query ) {
if (($query->is_main_query()) && (is_tax('conference')))
$query->set( 'posts_per_page', '10' );
$query->set( 'orderby', 'title' );
$query->set( 'order', 'ASC' );
}
Can you see why this isn't working as it should?
It's a shame this is not built into the UI like it is for Views 😉
Shane
Supporter
Languages:
Englisch (English )
Timezone:
America/Jamaica (GMT-05:00)
Hi there,
The issue here is that your if statement is not being evaluated.
Reason being that you did not enclose the statement with { }
Hence the query filters are not being evaluated.
Try using the code below. This should work:
if (($query->is_main_query()) && (is_tax('conference'))){
$query->set( 'posts_per_page', '10' );
$query->set( 'orderby', 'title' );
$query->set( 'order', 'ASC' );
}
Having an if statement will only work if you are only doing a single line evaluation.
Example:
if (($query->is_main_query()) && (is_tax('conference')))
$query->set( 'posts_per_page', '10' );
The above code will evaluate since it is a single line evaluation.
If you are using multi-lined evaluations you are required to use the { }
Wow thanks Shane, I didn't know that, it does make sense though.
It is working now, thanks so much 🙂
OK, this was helpful - would be great if there was a code snippet repository. Adding my input, just in case helps anyone else in the future too - sort order using a custom date field, code below worked for me.
//Order archive tax event by date
add_filter('pre_get_posts', 'order_tx_by_date');
function order_tx_by_date($q) {
if (($q->is_main_query()) && (is_tax('event-type'))) {
$q->set('orderby', 'meta_value');
$q->set('order', 'DESC');
$q->set('value', 'strtotime("00:00:00")');
$q->set('meta_key', 'wpcf-event-start-date');
}
return $q;
}