I have a Custom Post Type
called Book, and the link is: mywebsite.com/book/mybookname
I want to change this so that the link is mywebsite.com/mybookname
.
I have added the following code to change the link and it works as expected:
function books_theme_remove_slug( $post_link, $post, $leavename ) {
if ( 'book' != $post->post_type || 'publish' != $post->post_status ) {
return $post_link;
}
$post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );
return $post_link;
}
add_filter( 'post_type_link', 'books_theme_remove_slug', 10, 3 );
function books_theme_parse_request( $query ) {
if ( ! $query->is_main_query() || 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) {
return;
}
if ( ! empty( $query->query['name'] ) ) {
$query->set( 'post_type', array( 'post', 'book', 'page' ) );
}
}
add_action( 'pre_get_posts', 'books_theme_parse_request' );
The problem is that the old link(mywebsite.com/book/mybookname
) is still working. I'd like to make that link go to a 404 page without breaking the current links.
I tried the following but it breaks everything:
function books_theme_parse_request( $query ) {
if(isset($query->query['post_type']) && $query->query['post_type'] == 'book'){
global $wp_query;
$wp_query->set_404();
status_header( 404 );
get_template_part( 404 ); exit();
}
if ( ! $query->is_main_query() || 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) {
return;
}
if ( ! empty( $query->query['name'] ) ) {
$query->set( 'post_type', array( 'post', 'book', 'page' ) );
}
}
add_action( 'pre_get_posts', 'books_theme_parse_request' );
How do I delete old url?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…