How to implement automatic redirection when WordPress search results are unique

888u

Last update at :2024-07-09,Edit by888u

Have we seen that in some WP themes, when searching for content, if the result is only one record, it will automatically jump to this record. This kind of experience will be better. Do you know how to achieve these effects?

//Search the only jump By https://www.cnwper.com/wpsearch-301.html
add_action('template_redirect', 'redirect_single_post');
function redirect_single_post() {
if (is_search()) {
 global $wp_query;
if ($wp_query->post_count == 1 && $wp_query->max_num_pages == 1) {
wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );
 exit;
}
}
}

Here, we can put the code into the functions.php file and automatically achieve this effect.

Recommended site searches: check IP, how to rent foreign servers, US host rental, Hong Kong vps host rental, website space rental, Taiwan server rental, domain name query, domain name space agent, Singapore server, Hong Kong virtual host space,

How to implement automatic redirection when WordPress search results are unique

All copyrights belong to 888u unless special state
取消
微信二维码
微信二维码
支付宝二维码