• Đăng ký
  • Đăng nhập

Sitemap trong WordPress

📅 — 👀 1938 — 👦

Bài viết này sẽ giúp bạn hiểu rõ hơn về cấu trúc và tạo sitemap trong WordPress. Với bài viết này bạn có thể tùy chỉnh lại sitemap mặc định của WordPress mà không cần cài thêm plugin tạo sitemap.

Chú ý : Bài viết này chỉ nói về sitemap để lập chỉ mục cho Google Console, chứ không phải tạo trang Sitemap cho người dùng nhé.

Đường dẫn mặc định sitemap mà WordPress có dạng như sau : https://thichcode.net/wp-sitemap.xml

Sitemap trong WordPress - Hình 1

Tắt chức năng sitemap :

add_filter( 'wp_sitemaps_enabled', '__return_false' );

Tùy chỉnh sitemap bằng class :

//Khai báo class Sitemap
class KK_Sample_Posts_Sitemaps_Provider extends WP_Sitemaps_Provider {	
	public $name;

	public function __construct() {
		$this->name        = 'video';
		$this->object_type = 'video';
	}

	//Bắt buộc phải có hàm này
	public function get_url_list( $page_num, $subtype = '' ) {

		$args = $this->wp_query_args();
		$args['paged'] = $page_num;

		$query = new WP_Query( $args );

		$url_list = array();

		foreach ( $query->posts as $post ) {
			$sitemap_entry = [
				'loc' => user_trailingslashit( untrailingslashit( get_permalink( $post ) ) .'/video/' ),
			];

			$url_list[] = $sitemap_entry;
		}

		return $url_list;
	}

	//Bắt buộc phải có hàm này
	public function get_max_num_pages( $subtype = '' ) {
		$args                  = $this->wp_query_args();
		$args['fields']        = 'ids';
		$args['no_found_rows'] = false;

		$query = new WP_Query( $args );

		return $query->max_num_pages;
	}

	protected function wp_query_args(){
		return array(
			'orderby'                => 'ID',
			'order'                  => 'ASC',
			'post_type'              => 'post', //Lấy post theo custom post là video
			'posts_per_page'         => wp_sitemaps_get_max_urls( $this->object_type ),
			'post_status'            => array( 'publish' ),
			'no_found_rows'          => true,
			'update_post_term_cache' => false,
			'update_post_meta_cache' => false,
		);
	}
}

//Thêm tùy chỉnh sitemap bằng class KK_Sample_Posts_Sitemaps_Provider()
add_filter(
    'init',
    function() {
        $provider = new KK_Sample_Posts_Sitemaps_Provider();
	wp_register_sitemap_provider( $provider->name, $provider );
    }
);

Với đoạn code ở trên thì trong wp-sitemap sẽ xuất hiện thêm link sitemap là video (hình bên dưới)

Sitemap trong WordPress - Hình 2

Tắt sitemap người dùng :

add_filter(
    'wp_sitemaps_add_provider',
    function( $provider, $name ) {
        if ( 'users' === $name ) {
            return false;
        }
 
        return $provider;
    },
    10,
    2
);

Tắt sitemap cho trang (page post type):

add_filter(
    'wp_sitemaps_post_types',
    function( $post_types ) {
        unset( $post_types['page'] );
        return $post_types;
    }
);

Tắt sitemap cho thẻ (post_tag) :

add_filter(
    'wp_sitemaps_taxonomies',
    function( $taxonomies ) {
        unset( $taxonomies['post_tag'] );
        return $taxonomies;
    }
);

Thêm ngày sửa bài viết :

add_filter(
    'wp_sitemaps_posts_entry',
    function( $entry, $post ) {
        $entry['lastmod'] = $post->post_modified_gmt;
        return $entry;
    },
    10,
    2
);

Loại trừ một bài viết khỏi sitemap :

add_filter(
    'wp_sitemaps_posts_query_args',
    function( $args, $post_type ) {
        if ( 'post' !== $post_type ) {
            return $args;
        }
 
        $args['post__not_in'] = isset( $args['post__not_in'] ) ? $args['post__not_in'] : array();
        $args['post__not_in'][] = 123; // loại trừ bài viết có ID : 123
        return $args;
    },
    10,
    2
);

Hooks và Filters :

Tổng quan:

  • wp_sitemaps_enabled – Lọc xem Sitemap XML có được bật hay không.
  • wp_sitemaps_max_urls – Lọc số lượng URL tối đa được hiển thị trên sitemap.
  • wp_sitemaps_init – Kích hoạt tối ưu sitemap.
  • wp_sitemaps_index_entry – Lọc chỉ mục sitemap.

Providers (cung cấp):

  • wp_sitemaps_add_provider – Lọc cung cấp trước khi thêm vào.
  • wp_sitemaps_post_types – Lọc danh sách các loại bài đăng để đưa vào sitemap.
  • wp_sitemaps_posts_entry – Lọc chỉ cho bài viết cụ thể.
  • wp_sitemaps_posts_show_on_front_entry – Lọc mục nhập sitemap cho trang chủ khi tùy chọn ‘show_on_front’ bằng ‘posts’.
  • wp_sitemaps_posts_query_args – Lọc các đối số truy vấn cho các truy vấn sitemap loại bài đăng.
  • wp_sitemaps_posts_pre_url_list – Lọc danh sách URL của bài đăng trước khi nó được tạo (ngắn mạch).
  • wp_sitemaps_posts_pre_max_num_pages – Lọc số lượng trang tối đa trước khi nó được tạo (ngắn mạch).
  • wp_sitemaps_taxonomies – Lọc danh sách các đơn vị phân loại để đưa vào sitemap.
  • wp_sitemaps_taxonomies_entry – Lọc mục nhập sitemap cho một term riêng lẻ.
  • wp_sitemaps_taxonomies_query_args – Lọc các đối số truy vấn cho các cụm từ phân loại các truy vấn sitemap.
  • wp_sitemaps_taxonomies_pre_url_list – Lọc danh sách URL phân loại trước khi nó được tạo (ngắn mạch).
  • wp_sitemaps_taxonomies_pre_max_num_pages – Lọc số lượng trang tối đa trước khi nó được tạo (ngắn mạch).
  • wp_sitemaps_users_entry – Lọc mục nhập sơ đồ trang web cho một người dùng cá nhân.
  • wp_sitemaps_users_query_args – Lọc các đối số truy vấn cho các truy vấn sơ đồ trang web của người dùng.
  • wp_sitemaps_users_pre_url_list – Lọc danh sách URL của người dùng trước khi nó được tạo (ngắn mạch).
  • wp_sitemaps_users_pre_max_num_pages – Lọc số lượng trang tối đa trước khi nó được tạo (ngắn mạch).

Stylesheets (biểu định kiểu):

  • wp_sitemaps_stylesheet_css – Lọc CSS cho biểu định kiểu sơ đồ trang web.
  • wp_sitemaps_stylesheet_url – Lọc URL cho biểu định kiểu sơ đồ trang web.
  • wp_sitemaps_stylesheet_content – Lọc nội dung của biểu định kiểu sơ đồ trang web.
  • wp_sitemaps_stylesheet_index_url – Lọc URL cho biểu định kiểu chỉ mục sơ đồ trang web.
  • wp_sitemaps_stylesheet_index_content – Lọc nội dung của biểu định kiểu chỉ mục sơ đồ trang web.

Tạo thủ công file sitemap.xml

Ngoài ra, nếu bạn không thích dùng wp-sitemap.xml thì ở đây có 01 đoạn code cơ bản để tạo file sitemap.xml trong WordPress, nhằm giúp cho google index các bài viết mới của ta một cách tự động. Bạn chỉ cần copy đoạn code này vào file function.php là được.


/****************************************************
* Tạo file sitemap.xml để nhúng vào Google Search Console - Code by ThichCode.NET
*****************************************************/
function kk_xml_sitemap() {
  $postsForSitemap = get_posts(array(
    'numberposts' => -1,
    'orderby' => 'modified',
    'post_type'  => array('post','page'),
    'order'    => 'DESC'
  ));
  $sitemap = '<?xml version="1.0" encoding="UTF-8"?>';
  $sitemap .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
  foreach($postsForSitemap as $post) {
    setup_postdata($post);
    $postdate = explode(" ", $post->post_modified);
    $sitemap .= '<url>'.
      '<loc>'. get_permalink($post->ID) .'</loc>'.
      '<lastmod>'. $postdate[0] .'</lastmod>'.
      '<changefreq>monthly</changefreq>'.
    '</url>';
  }
  $sitemap .= '</urlset>';
  $fp = fopen(ABSPATH . "sitemap.xml", 'w');
  fwrite($fp, $sitemap);
  fclose($fp);
}
add_action("publish_post", "kk_xml_sitemap");
add_action("publish_page", "kk_xml_sitemap");

Trả lời


📁 Document
🔖