Если у вас новостной сайт, то для укрепления своих позиций в результатах поисковых систем используйте Sitemap для новостей (Google News Sitemap), чтобы информировать Google о появлении новых статей и предоставлять о них дополнительную информацию.
Вы можете добавить определенные теги новостей в существующий файл Sitemap или создать отдельный файл Sitemap.
Отдельный файл Sitemap для новостей, по рекомендации Google, может улучшить отслеживание вашего контента в поиске с помощью Search Console. Подробности на сайте Google
Добавьте код в файл function.php, и обновите раздел “Постоянные ссылки” на своем сайте.
Добавьте файл Sitemap в Search Console.
Сам файл будет доступен по адресу: https://www.yorsite.com/wp-sitemap-google-news.xml
Протестировано:
WordPress 6.4.2
PHP 7.4
/**
* Create rewrite rule.
* the file will be available at https://www.yorsite.com/wp-sitemap-google-news.xml
*
*/
add_action( 'init', 'wphaf_google_news_rewrite_rule' );
function wphaf_google_news_rewrite_rule() {
add_rewrite_rule( '^wp-sitemap-google-news.xml$', 'index.php?google_news=index', 'top' );
add_filter( 'query_vars', function( $vars ) {
$vars[] = 'google_news';
return $vars;
}
);
}
/**
* Render xml for sitemap.
*
*/
function wphaf_google_news_render_sitemap() {
global $wp_query;
if ( get_query_var( 'google_news' ) != false && get_query_var( 'google_news' ) != '' ) {
ob_start();
echo sprintf(
'%1$s%2$s',
'<?xml version="1.0" encoding="UTF-8" ?>',
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:news="http://www.google.com/schemas/sitemap-news/0.9">'
);
$args = array(
'posts_per_page' => 20,
'orderby' => 'modified',
'order' => 'DESC',
'post_type' => array( 'post' ),
'no_found_rows' => true,
'ignore_sticky_posts' => true,
'date_query' => array(
'after' => '2 day ago'
)
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
$date = new DateTime( $query->post->post_date, new DateTimeZone( 'Europe/Berlin' ) );
$format = 'c';
?>
<url>
<loc><?php echo get_permalink( $query->post->ID ); ?></loc>
<news:news>
<news:publication>
<news:name><?php echo get_bloginfo( 'name', 'display' ); ?></news:name>
<news:language>ru</news:language>
</news:publication>
<news:publication_date><?php echo $date->format( $format ); ?></news:publication_date>
<news:title><?php echo get_the_title( $query->post->ID ); ?></news:title>
</news:news>
</url>
<?php
}
}
wp_reset_postdata();
?>
</urlset>
<?php
$sitemap_xml = ob_get_contents();
ob_end_clean();
return $sitemap_xml;
}
}
/**
* Output render xml file.
*
*/
add_action( 'template_redirect', 'wphaf_google_news_template_redirect', 2 );
function wphaf_google_news_template_redirect() {
global $wp_query;
if ( get_query_var( 'google_news' ) != false && get_query_var( 'google_news' ) != '' ) {
header( 'Content-Type: application/xml; charset=UTF-8' );
echo wphaf_google_news_render_sitemap();
exit();
}
}