wp_sitemaps_posts_entry
云策文档标注
概述
wp_sitemaps_posts_entry 是一个 WordPress 过滤器钩子,用于修改单个文章在站点地图中的条目。它允许开发者自定义文章在站点地图中的表示,如添加或修改属性。
关键要点
- 这是一个过滤器钩子,用于过滤单个文章的站点地图条目。
- 参数包括 $sitemap_entry(文章站点地图条目数组)、$post(WP_Post 对象)和 $post_type(文章类型名称)。
- 在 WordPress 5.5.0 版本中引入。
- 常用于添加 lastmod 日期或修改文章 URL 等场景。
代码示例
// 示例1:添加最后修改日期到站点地图条目
add_filter( 'wp_sitemaps_posts_entry', function( $entry, $post ) {
$entry['lastmod'] = date( DATE_W3C, strtotime( $post->post_modified_gmt ) );
return $entry;
}, 10, 2 );
// 示例2:在 WP Multisites 中修改文章 URL
add_filter( 'wp_sitemaps_posts_entry', 'wpdocs_sitemaps_posts_entry_callback', 10, 2 );
function wpdocs_sitemaps_posts_entry_callback( $sitemap_entry, $post ) {
switch_to_blog( get_blog_id_from_url( $_SERVER['HTTP_HOST'] ) );
$sitemap_entry['loc'] = get_permalink( $post );
return $sitemap_entry;
}
原文内容
Filters the sitemap entry for an individual post.
Parameters
$sitemap_entryarray-
Sitemap entry for the post.
$postWP_Post-
Post object.
$post_typestring-
Name of the post_type.
Source
$sitemap_entry = apply_filters( 'wp_sitemaps_posts_entry', $sitemap_entry, $post, $post_type );
Changelog
| Version | Description |
|---|---|
| 5.5.0 | Introduced. |
Skip to note 3 content
Stonehenge Creations
To add the last modifed date to your XML sitemap, Google wants the date in W3C format.
add_filter( 'wp_sitemaps_posts_entry', function( $entry, $post ) { $entry['lastmod'] = date( DATE_W3C, strtotime( $post->post_modified_gmt ) ); return $entry; }, 10, 2 );Skip to note 4 content
Harit Panchal
To alter the post URLs in WP Multisites,
add_filter( 'wp_sitemaps_posts_entry', 'wpdocs_sitemaps_posts_entry_callback', 10, 2 ); function wpdocs_sitemaps_posts_entry_callback( $sitemap_entry, $post ) { switch_to_blog( get_blog_id_from_url( $_SERVER['HTTP_HOST'] ) ); $sitemap_entry['loc'] = get_permalink( $post ); return $sitemap_entry; }