Products
GG网络技术分享 2025-03-18 16:13 7
只用WordPress定时任务去生成sitemap.xml,这样比网上很多方法是在保存、发布文章时生成xml好一些,不会造成处理文章卡的现象。在WordPress主题文件functions.php中或者使用Code Snippets插件添加自定义代码:
// 判断定时计划是否存在
if ( ! wp_next_scheduled( 'sitemap_xml' ) ) {
wp_schedule_event( time(), 'twicedaily', 'sitemap_xml' ); // 每天两次
}
add_action( 'sitemap_xml', 'sitemap_xml_func' );
// 定时计划执行函数
function sitemap_xml_func() {
// 获取文章数量
$count_posts = wp_count_posts();
if ( $count_posts ) {
$published_posts = $count_posts->publish;
$sitemap_num = $published_posts / 3000; // 每个xml文件最多包含3000篇文章
$sitemap_num = ceil($sitemap_num);
// 创建xml文件
for ($i = 1; $i <= $sitemap_num; $i++) {
$postsForSitemap = get_posts(array(
'numberposts' => 3000,
'orderby' => 'modified',
'post_type' => array('post'),
'order' => 'DESC',
'offset' => 3000 * ($i - 1)
));
$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);
$post_url = get_permalink($post->ID);
$post_date = get_the_modified_date( 'c',$post->ID );
$sitemap .= '<url>'.
'<loc>'. $post_url .'</loc>'.
'<lastmod>'. $post_date .'</lastmod>'.
// '<lastmod>'. $postdate[0] .'</lastmod>'.
// '<changefreq>monthly</changefreq>'.
'</url>';
}
$sitemap .= '</urlset>';
$fp = fopen(ABSPATH . "sitemap-".$i.".xml", 'w');
fwrite($fp, $sitemap);
fclose($fp);
}
// 创建sitemap.xml文件
$sitemap_all = '<?xml version="1.0" encoding="UTF-8"?>';
$sitemap_all .= '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
for ($i = 1; $i <= $sitemap_num; $i++) {
$sitemap_all .= '<sitemap>'.
'<loc>'. get_bloginfo('url') .'/sitemap-'.$i.'.xml</loc>'.
'<lastmod>'. date('c') .'</lastmod>'.
'</sitemap>';
}
$sitemap_all .= '</sitemapindex>';
$fp = fopen(ABSPATH . "sitemap.xml", 'w');
fwrite($fp, $sitemap_all);
fclose($fp);
}
}近日很多朋友咨询进行文章数量统计的wordpress函数wp_count_posts()是什么?今天小编为大家简单分享一下。wp_count_posts()是用于统计指定文章类型文章数量的wordpress函数,通过wp_count_posts()函数可以统计所有类型的文章数量,如post、page或自定义文章类型post_type等,还可以计算指定状态的文章,如已发布、定时发布、草稿、待审、私有等。
代码结构:
<?phpwp_count_posts(\'type\',\'readable\');?>
参数说明
type-(字符)可选,指定文章的类型(post_type),如post、page或其它自定义文章类型,默认为post。
perm-(字符)可选,该参数可将私密文章状态算入文章状态中,使用“readable”并要求用户登录,默认为空。
返回值
wp_count_posts()的返回值为数组
1 | stdClass Object( [publish] => 11//已发布 [future] => 0//定时发布 [draft] => 0//草稿 [pending] => 0//待审 [private] => 0//私有 [trash] => 0//垃圾箱 [auto-draft] => 34//自动草稿 [inherit] => 0//修订版本 [request-pending] => 0 [request-confirmed] => 0 [request-failed] => 0 [request-completed] => 0) |
Demand feedback