我有一個Custom Post Type
稱爲書,並且鏈接是:mywebsite.com/book/mybookname
如何在重寫URL以排除子彈後刪除舊的自定義帖子類型固定鏈接?
我想改變這一點,以便鏈接mywebsite.com/mybookname
。
我加入以下代碼更改的鏈接,它按預期工作:
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');
的問題是,舊的鏈接(mywebsite.com/book/mybookname
)仍正常工作。我想讓鏈接轉到404頁面而不會打破當前鏈接。
我嘗試以下,但它打破了一切:
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');
如何刪除舊的網址是什麼?
不知道這事,但你爲什麼要使用書本 - 西班牙語單詞>時,根據您的其他代碼你正在使用您的文章類型英文單詞LIBRO? – fjoe
你把你試過的代碼放在哪裏?我想應該增加更多的條件,比如要知道這是網站的管理員或公共部分,頁面的類型等。順便說一句,它是如何打破一切的?錯誤代碼? – Kaddath
fjoe:它是一個西班牙語網站,我在這裏使用了書籍,因爲我認爲如果說英語的人可以很容易地獲得幫助,我更容易獲得幫助,所以我編輯了它。 Kaddath,我試過的代碼是在books_theme_parse_request($ query)中。虐待編輯我的帖子,使其更清晰。它會讓它剎車,因爲在任何地方顯示的書都會變成404錯誤。我只想要與原始網址的書單是404 – Aschab