WP Query by Gutenberg block and get its attribute

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'];
}

Leave a Comment

tech