First we look into the wp_get_post_autosave
function
It’s informative to see how the core function wp_get_post_autosave()
uses
the wp_get_post_revisions()
function.
It loops over all revisions from
$revisions = wp_get_post_revisions(
$post_id,
array(
'check_enabled' => false
)
);
and then uses:
foreach ( $revisions as $revision ) {
if ( false !== strpos( $revision->post_name, "{$post_id}-autosave" ) ) {
if ( $user_id && $user_id != $revision->post_author )
continue;
return $revision;
}
}
to return the first revision with a slug containing "{$post_id}-autosave"
and where the $user_id
possibly matches it’s author.
Alternative
Now wp_get_post_revisions()
is a wrapper for get_children()
, so I wonder why it has to fetch all the revisions for the given post, before filtering out a single one. Why not try to fetch it directly, only what’s needed? When we try e.g. the following (PHP 5.4+):
$revisions = wp_get_post_revisions(
$post_id,
[
'offset' => 1, // Start from the previous change (ofset changed to offset)
'posts_per_page' => 1, // Only a single revision
'name' => "{$post_id}-autosave-v1",
'check_enabled' => false,
]
);
then the posts_per_page
will not have any effect. After playing around with this I managed to get the following to work with the posts_per_page
argument:
$revisions = wp_get_post_revisions(
$post_id,
[
'offset' => 1, // Start from the previous change
'posts_per_page' => 1, // Only a single revision
'post_name__in' => [ "{$post_id}-autosave-v1" ],
'check_enabled' => false,
]
);
Get only the previous revision
Now we can adjust the above to only fetch the previous revision, i.e. that’s not an auto-save:
$revisions = wp_get_post_revisions(
$post_id,
[
'offset' => 1, // Start from the previous change
'posts_per_page' => 1, // Only a single revision
'post_name__in' => [ "{$post_id}-revision-v1" ],
'check_enabled' => false,
]
);
Here we target the {$post_id}-revision-v1
slug.
Note the here we use the v1
, but we could adjust that if needed later on.
Example
So to finally answer your question, here’s a suggestion:
$show = get_post_meta( get_the_ID(), 'somekey', true );
if( $show )
{
// Template part
get_template_part( 'template-parts/content' );
}
else
{
// Fetch the previous revision only
$revisions = wp_get_post_revisions(
get_the_ID(),
[
'offset' => 1, // Start from the previous change
'posts_per_page' => 1, // Only a single revision
'post_name__in' => [ sprintf( "%d-revision-v1", get_the_ID() ) ],
'check_enabled' => false,
]
);
if( $revisions )
{
$post = reset( $revisions );
setup_postdata( $post );
// Template part
get_template_part( 'template-parts/content' );
wp_reset_postdata();
}
else
{
// Some fallback here
}
}
Hopefully you can adjust it further to your needs!