I'd like to combine/refactor (if possible) these 2 functions into 1 since their scope is narrowly focused to one tax on my site. Purpose is to redirect links to a taxonomy term to the first (oldest) post in that category in the most efficient way possible:
function redirect_series() {
if (is_tax('series')) {
global $post;
wp_safe_redirect(get_permalink($post->ID));
die;
}
}
add_action('template_redirect','redirect_series');
function order_by_date_callback ( $query ) {
if (($query->is_main_query()) && (is_tax('series'))) {
$query->set( 'orderby', 'date' );
$query->set( 'order', 'ASC' );
}
}
add_action( 'pre_get_posts', 'order_by_date_callback' );
My Answer:
Yes, these two functions can be combined into one. Here is an example of how you can combine them:
php
function redirect_series() {
if (is_tax('series')) {
$posts = get_posts(array(
'post_type' => 'post',
'posts_per_page' => 1,
'tax_query' => array(
array(
'taxonomy' => 'series',
'field' => 'slug',
'terms' => get_query_var('series')
)
),
'orderby' => 'date',
'order' => 'ASC'
));
if ($posts) {
wp_safe_redirect(get_permalink($posts[0]->ID));
exit;
}
}
}
This combined function first retrieves the oldest post in the specified taxonomy term using `get_posts` with the appropriate parameters. It then checks if any posts were found and redirects to the permalink of the oldest post if one exists.
Rate this post
3 of 5 based on 9561 votesComments