WordPress 有一个权威 URL(Canonical URL)的概念,可以帮你避免一些 404 问题,跳转到正确的页面。但是如果你的博客有多个 post type 的话,这样导向会失效,我们可以在当前主题的 functions
文件中添加如下代码,提高 404 页面导向正确的页面的效率:
//解决日志改变 post type 之后跳转错误的问题,
add_action( 'template_redirect', 'wpjam_old_slug_redirect');
function wpjam_old_slug_redirect() {
global $wp_query;
if ( is_404() && '' != $wp_query->query_vars['name'] ) :
global $wpdb;
$query = $wpdb->prepare("SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_wp_old_slug' AND meta_value = %s", $wp_query->query_vars['name']);
$id = (int) $wpdb->get_var($query);
if ( !$id ){
$link = wpjam_redirect_guess_404_permalink();
}else{
$link = get_permalink($id);
}
if ( !$link )
return;
wp_redirect( $link, 301 );
exit;
endif;
}
function wpjam_redirect_guess_404_permalink() {
global $wpdb, $wp_rewrite;
if ( get_query_var('name') ) {
$where = $wpdb->prepare("post_name LIKE %s", like_escape( get_query_var('name') ) . '%');
$post_id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE $where AND post_status = 'publish'");
if ( ! $post_id )
return false;
if ( get_query_var( 'feed' ) )
return get_post_comments_feed_link( $post_id, get_query_var( 'feed' ) );
elseif ( get_query_var( 'page' ) )
return trailingslashit( get_permalink( $post_id ) ) . user_trailingslashit( get_query_var( 'page' ), 'single_paged' );
else
return get_permalink( $post_id );
}
return false;
}
该功能已经整合到 WPJAM Basic 插件中,并已免费提供下载,简单勾选或者设置下即可开启!