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?

1 Answer 1


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'];
  • note that this will not work in modern WP as the youtube block was retired in favour of a youtube block variant of the 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
    – Tom J Nowell
    Nov 19, 2021 at 14:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.