函数文档

_update_posts_count_on_transition_post_status()

💡 云策文档标注

概述

_update_posts_count_on_transition_post_status() 是一个 WordPress 函数,用于在文章状态变更时更新当前站点的文章计数。它通过检查状态变化和文章类型来确保计数准确。

关键要点

  • 函数在文章状态从 'publish' 变为非 'publish' 或反之时触发更新。
  • 仅处理 'post' 类型的文章,忽略其他自定义文章类型。
  • 如果新旧状态相同,函数会提前返回,避免不必要的操作。
  • 新增了 $post 参数,允许传入 WP_Post 对象以增强灵活性。

代码示例

function _update_posts_count_on_transition_post_status( $new_status, $old_status, $post = null ) {
    if ( $new_status === $old_status ) {
        return;
    }

    if ( 'post' !== get_post_type( $post ) ) {
        return;
    }

    if ( 'publish' !== $new_status && 'publish' !== $old_status ) {
        return;
    }

    update_posts_count();
}

注意事项

  • 函数依赖于 update_posts_count() 来实际执行计数更新,确保该函数可用。
  • 在 WordPress 4.9.0 版本中引入了 $post 参数,以支持更精确的文章处理。
  • 开发者应确保在适当的 Hook(如 transition_post_status)中调用此函数。

📄 原文内容

Handler for updating the current site’s posts count when a post status changes.

Parameters

$new_statusstringrequired
The status the post is changing to.
$old_statusstringrequired
The status the post is changing from.
$postWP_Postoptional
Post object

Default:null

Source

function _update_posts_count_on_transition_post_status( $new_status, $old_status, $post = null ) {
	if ( $new_status === $old_status ) {
		return;
	}

	if ( 'post' !== get_post_type( $post ) ) {
		return;
	}

	if ( 'publish' !== $new_status && 'publish' !== $old_status ) {
		return;
	}

	update_posts_count();
}

Changelog

Version Description
4.9.0 Added the $post parameter.
4.0.0 Introduced.