函数文档

wp_get_latest_revision_id_and_total_count()

💡 云策文档标注

概述

wp_get_latest_revision_id_and_total_count() 函数用于获取文章的最新修订版本ID和修订总数。它接受一个可选参数指定文章,返回包含最新ID和总数的数组,或在错误时返回WP_Error。

关键要点

  • 参数 $post 可选,可以是文章ID或WP_Post对象,默认为全局$post
  • 返回关联数组,包含latest_id(最新修订ID,若无修订则为0)和count(修订总数)
  • 如果文章不存在或未启用修订,函数返回WP_Error
  • 内部使用WP_Query查询修订,并检查wp_revisions_enabled()

代码示例

function wp_get_latest_revision_id_and_total_count( $post = 0 ) {
	$post = get_post( $post );

	if ( ! $post ) {
		return new WP_Error( 'invalid_post', __( 'Invalid post.' ) );
	}

	if ( ! wp_revisions_enabled( $post ) ) {
		return new WP_Error( 'revisions_not_enabled', __( 'Revisions not enabled.' ) );
	}

	$args = array(
		'post_parent'         => $post->ID,
		'fields'              => 'ids',
		'post_type'           => 'revision',
		'post_status'         => 'inherit',
		'order'               => 'DESC',
		'orderby'             => 'date ID',
		'posts_per_page'      => 1,
		'ignore_sticky_posts' => true,
	);

	$revision_query = new WP_Query();
	$revisions      = $revision_query->query( $args );

	if ( ! $revisions ) {
		return array(
			'latest_id' => 0,
			'count'     => 0,
		);
	}

	return array(
		'latest_id' => $revisions[0],
		'count'     => $revision_query->found_posts,
	);
}

注意事项

  • 函数在WordPress 6.1.0版本中引入
  • 相关函数包括wp_revisions_enabled()、get_post()和WP_Query
  • 被多个函数如wp_get_post_revisions_url()和REST API控制器使用

📄 原文内容

Returns the latest revision ID and count of revisions for a post.

Parameters

$postint|WP_Postoptional
Post ID or WP_Post object. Default is global $post.

Return

array|WP_Error Returns associative array with latest revision ID and total count, or a WP_Error if the post does not exist or revisions are not enabled.

  • latest_id int
    The latest revision post ID or 0 if no revisions exist.
  • count int
    The total count of revisions for the given post.

Source

function wp_get_latest_revision_id_and_total_count( $post = 0 ) {
	$post = get_post( $post );

	if ( ! $post ) {
		return new WP_Error( 'invalid_post', __( 'Invalid post.' ) );
	}

	if ( ! wp_revisions_enabled( $post ) ) {
		return new WP_Error( 'revisions_not_enabled', __( 'Revisions not enabled.' ) );
	}

	$args = array(
		'post_parent'         => $post->ID,
		'fields'              => 'ids',
		'post_type'           => 'revision',
		'post_status'         => 'inherit',
		'order'               => 'DESC',
		'orderby'             => 'date ID',
		'posts_per_page'      => 1,
		'ignore_sticky_posts' => true,
	);

	$revision_query = new WP_Query();
	$revisions      = $revision_query->query( $args );

	if ( ! $revisions ) {
		return array(
			'latest_id' => 0,
			'count'     => 0,
		);
	}

	return array(
		'latest_id' => $revisions[0],
		'count'     => $revision_query->found_posts,
	);
}

Changelog

Version Description
6.1.0 Introduced.