If the rest of your function works you just need to add a call to wp_safe_redirect and hook the whole thing into WordPress. I think that the first hook that will have a populated $wp_query
is wp
. So alter the last part of your function...
if($max_page < $paged){
wp_safe_redirect(get_bloginof('url'),'301');
}
And then add the following after (outside) the function.
add_action('wp','redirect_tags');
I think that should do it. You can setup infinite redirect loops so be careful.
Edit: The problem is the is_paged()
check at the top of your function. If you try to access a pagination page that doesn't exist is_paged()
returns false
and none of the rest of your function runs. Remove that check, and hook to template_redirect
. I tested this and it does work. In other words...
function redirect_tags() {
if (is_main_query() && !is_singular() ) {
global $wp_query;
$paged = intval(get_query_var('paged'));
$max_page = $wp_query->max_num_pages;
if ( ($max_page < $paged) ) {
wp_safe_redirect(get_bloginfo('url'),'301');
}
}
}
add_filter('template_redirect','redirect_tags');