I need to fetch on the front page youtube video from the latest post where was used gutenberg youtube block.
I guess I need:
1) query such posts
2) extract the youtube URL from the block
Is there a way how to do that?
After hours of googling I came up with following solution. Maybe once will help to someone.
1) query post where is used gutenberg youtube block:
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
's' => 'core-embed/youtube',
'posts_per_page' => 1
);
$query = new WP_Query($args);
2) extract the URL from youtube block of the post
$post_id = 117;
$post = get_post($post_id);
$blocks = parse_blocks( $post->post_content );
function findYoutubeBlock(array $blocks) {
return $blocks['blockName'] == 'core-embed/youtube';
}
if (has_block('core-embed/youtube', $post_id)) {
$youtube_block = reset(array_filter($blocks, 'findYoutubeBlock'));
$youtube_url = $youtube_block['attrs']['url'];
}
core/embed
block. It would be more efficient and reliable to store a term/flag named has-video
in a private taxonomy when the post is saved or updated. This would also give you a screen in WP Admin that shows all posts that have this, as well as make the frontend WP_Query
significantly faster, and avoid having to parse blocks a second time on the frontend