Latest Post

Tăng thứ hạng và truy cập tự nhiên với 10 phương pháp SEO hay nhất Kiếm Tiền Online (mmo): Khái Niệm và Các Hình Thức Phổ Biến

Khi bạn tạo một loại bài đăng tùy chỉnh (Custom Post Type) mới trong WordPress, Permalink của nó sẽ được cấu hình theo cấu trúc mặc định như sau:

https://site-url/{post-type-slug}/{post-title}

VD: Với Custom Post Type là Book chúng ta có cấu trúc đường dẫn là:

https://site-url/book/book-title

Nếu bạn muốn chuyển về kiểu đường dẫn giống các Post thông thường trên WordPress là:

https://site-url/book-title

thì chúng ta cần can thiệu vào 2 hook sau.

Dưới dây là đoạn code xử lý xóa bỏ {post-type-slug}

1. Xóa bỏ slug trên Permalink

<?php

/**
 * Remove the slug from published post permalinks. Only affect our custom post type, though.
 */
function vinasupport_remove_custom_post_type_slug( $post_link, $post ) {

    if ( 'book' === $post->post_type && 'publish' === $post->post_status ) {
        $post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );
    }

    return $post_link;
}
add_filter( 'post_type_link', 'vinasupport_remove_custom_post_type_slug', 10, 2 );

2. Cập nhật xử lý Post Type của WordPress

Nếu người dùng truy cập vào một liên kết cố định (Permalink) sau khi nó đã bị rút gọn, họ sẽ gặp lỗi 404. Điều quan trọng là chúng ta cần xử lý để WordPress có thể hiểu và nhận dạng liên kết cố định mới cho Custom Post Type.

<?php

/**
 * Have WordPress match postname to any of our public post types (post, page, race).
 * All of our public post types can have /post-name/ as the slug, so they need to be unique across all posts.
 * By default, WordPress only accounts for posts and pages where the slug is /post-name/.
 *
 * @param $query The current query.
 */
function vinasupport_add_post_names_to_main_query( $query ) {

  // Bail if this is not the main query.
  if ( ! $query->is_main_query() ) {
    return;
  }

  // Bail if this query doesn't match our very specific rewrite rule.
  if ( ! isset( $query->query['page'] ) || 2 !== count( $query->query ) ) {
    return;
  }

  // Bail if we're not querying based on the post name.
  if ( empty( $query->query['name'] ) ) {
    return;
  }

  // Add CPT to the list of post types WP will include when it queries based on the post name.
  $query->set( 'post_type', array( 'post', 'page', 'book' ) );
}
add_action( 'pre_get_posts', 'vinasupport_add_post_names_to_main_query' );

Sau đó truy cập vào trang quản trị của WordPress => [ Settings ] => [ Permalinks ] để update lại cấu trúc link

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *