Hi You, I am Tade

You are here: Home / Wordpress / Wordpress nâng cao / Xóa slug trên custom post và custom taxonomy: Phần 1

Xóa slug trên custom post và custom taxonomy: Phần 1

11 March, 2017 by Hoàng Thức

Nhằm giúp các bạn tối ưu đường dẫn 1 cách gọn nhất khi tạo các custom post mới. Mình có làm 1 tus cách xóa slug cho trang single và category khi tạo custom post, mà wordpress chỉ hổ trợ cho 2 loại là post và page.

Đầu tiên về custom post (nếu bạn nào chưa biết về custom post có thể xem bài viết trước của mình).

1.Xóa slug trên custom post trong trang single:

Link custom post single ban đầu: https://hoangthuc.com/report/bao-cao-thu-chi/

Link custom post single cần thay thành: https://hoangthuc.com/bao-cao-thu-chi/

Custom post type mình làm ở đây là “report” nếu làm bạn có thể tùy biến custom post này. Các bạn vào file fucntions.php và thêm đoạn code có định dạng bên dưới.

// remove slug custom_post type
function na_remove_slug( $post_link, $post, $leavename ) {

    if ( 'report' != $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', 'na_remove_slug', 10, 3 );

Note* Trong phần này bạn sẽ dung hàm na_remove_slug để filter vào hook post_type_link

2. Xữ lý lỗi 301 redirect khi chuyển:

Trong quá trình remove slug như bước 1 wp sẽ xuất hiện lỗi 301 không tìm thấy trang. Cách xữ lý.

function na_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', 'report', 'page' ) );
    }
}
add_action( 'pre_get_posts', 'na_parse_request' );

Sau đó các bạn và Setting => Permalink và Save button lại để hoàn tất.

 

Chúc các bạn thành công !

 

Filed Under: Custom post wordpress, Wordpress, Wordpress nâng cao Tagged With: Custom post wp, Thủ thuật wordpress, wordpress nâng cao

  • Home
  • About
  • Donate

Danh mục

  • Blog
  • Lập trình
  • Laravel
  • MYSQL
  • Php
  • Thủ thuật máy tính
  • Vps
    • DirectAdmin
  • Wordpress
    • Plugin wordpress
    • Wordpress căn bản
    • Wordpress nâng cao
      • Custom post wordpress

Archives

  • October 2021
  • January 2021
  • December 2020
  • November 2020
  • September 2020
  • August 2020
  • September 2019
  • August 2019
  • July 2019
  • June 2018
  • August 2017
  • July 2017
  • June 2017
  • May 2017
  • March 2017
  • November 2016
  • September 2016
  • July 2016
  • June 2016
  • May 2016
  • April 2016
  • March 2016
  • January 2016
  • December 2015
  • May 2015
  • April 2015
Copyright © 2023 · HoangThuc.com · Genesis Framework