WP Query by Gutenberg block and get its attribute

admin2025-06-02  0

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?

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?

Share Improve this question edited Mar 2, 2019 at 19:20 Tomáš Vavřinka asked Mar 2, 2019 at 14:30 Tomáš VavřinkaTomáš Vavřinka 1979 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 3

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'];
}
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748847713a314223.html

最新回复(0)