我有一个称为“运动”的分类法,包括足球、橄榄球、网球。。。我想实现的是,当(例如)一篇有“足球”一词的帖子被丢弃,访问者尝试访问它时,它将被重定向到(出于SEO目的):mywebsite。com/sports/football/。
我花了很多天的时间想知道如何做到这一点,但都没有成功。下面是我尝试的代码示例:
function redirect_trashed_posts(){
if( is_404() ){
global $wp_query, $wpdb, $post;
$post_id = $post->ID;
if( is_object_in_term( $post_id, \'sports\' ) ) {
$terms = get_the_terms( $post_id, \'sports\' );
$term = array_shift( $terms );
$slug = $term->slug;
$redirect_to = get_option(\'siteurl\') . \'/sports/\' . $slug . \'/\';
wp_redirect( $redirect_to, 301 );
exit();
}
}
}
add_action(\'template_redirect\', \'redirect_trashed_posts\');
主要问题是,我无法获取垃圾帖子的ID,因此,用于检查帖子是否属于“体育”的if语句不起作用,“get\\u The\\u terms()”没有返回任何内容。我还试图通过slug获取数据,但没有成功。
谢谢你的帮助。
SOLUTION
function redirect_trashed_posts(){
if( is_404() ){ // if page does not exist anymore
global $wpdb; // so we can talk to db
// getting current slug__trashed
// WP append __trashed to trshed posts
$trashed_post_slug = trim($_SERVER[\'REQUEST_URI\'], \'/\') . \'__trashed\';
$post_data = $wpdb->get_row( // requesting ID & post_status from DB
"
SELECT ID, post_status
FROM $wpdb->posts
WHERE post_name = \'$trashed_post_slug\'
"
);
$post_id = $post_data->ID; // Getting the ID
$post_status = $post_data->post_status; // Grabbing the post_status
if ( $post_status == \'trash\'){ // if we are currently on a trashed post
$terms = get_the_terms( $post_id, \'sports\'); // Getting Term, it\'s an array of objects
$term = array_shift( $terms ); // Getting first object. I have just one
$term_slug = $term->slug; // Getting term slug
$redirect_to = get_option(\'siteurl\') . \'/sports/\' . $term_slug . \'/\'; // full url
wp_redirect( $redirect_to, 301 ); // 301 redirection
exit();
}
}
}
add_action(\'template_redirect\', \'redirect_trashed_posts\');
谢谢:D