This functionality appears to be exclusively a feature of the block editor. It’s not especially clever either. All it does is check that if the post has 1 or 2 blocks (and no more), and then maps the first block against a list of appropriate post formats, like so:
switch ( name ) {
case 'core/image':
return 'image';
case 'core/quote':
case 'core/pullquote':
return 'quote';
case 'core/gallery':
return 'gallery';
case 'core/video':
case 'core-embed/youtube':
case 'core-embed/vimeo':
return 'video';
case 'core/audio':
case 'core-embed/spotify':
case 'core-embed/soundcloud':
return 'audio';
}
This is part of the getSuggestedPostFormat()
selector function that’s part of the core/editor
data store. You can see the full source in the Gutenberg repository here. This seems like a good overview of what the data stores in the block editor are.
To use this function in JS in the editor you could use:
wp.data.select('core/editor').getSuggestedPostFormat();
The logic is simple enough that it’s trivial to implement in PHP with parse_blocks()
, but since it’s based on the blocks used it would only be useful for content built with the block editor.
function wpse_346884_get_suggested_post_format( $content ) {
if ( ! has_blocks( $content ) ) {
return null;
}
$block = null;
$blocks = parse_blocks( $post->post_content );
if ( 1 === count( $blocks ) ) {
$block = $blocks[0]['blockName'];
}
if ( 2 === count( $blocks ) ) {
if ( 'core/paragraph' === $blocks[1]['blockName'] ) {
$block = $blocks[0]['blockName'];
}
}
switch ( $block ) {
case 'core/image':
return 'image';
case 'core/quote':
case 'core/pullquote':
return 'quote';
case 'core/gallery':
return 'gallery';
case 'core/video':
case 'core-embed/youtube':
case 'core-embed/vimeo':
return 'video';
case 'core/audio':
case 'core-embed/spotify':
case 'core-embed/soundcloud':
return 'audio';
}
return null;
}
Then you might want to implement some additional logic to make sure the theme supports the returned post type.