1

I need to get information on front page about post - if it has gallery or video or both, how to find this information?

2

1 Answer 1

4

One can use the built-in has_block( $block_type, $post ) function to check for specific blocks.

The first input argument is the block type in <!-- wp:{$block_type} --> and the second one is the post object.

To find the corresponding block type, we can view it in the Code Editor view via the shortcut:

Ctrl + Shift + Alt + M

or via the settings:

code view

For example the gallery block will show as:

Code view

Example: Within The Loop

Checking for wp:gallery and wp:video blocks, within the loop, the corresponding block types are gallery and video:

if ( has_block( 'video' ) && has_block( 'gallery' ) ) {
   // ...
}

Example: Outside The Loop

For a given post object, we can use the second input argument of has_block() to determince if the post contains the wp:gallery and wp:video blocks:

$mypost = get_post( 123 );

if ( has_block( 'video', $mypost ) && has_block( 'gallery', $mypost ) ) {
   // ...
}

Example: Custom Block Within The Loop

Checking the content for a custom block with namespace: <!-- wp:custom/block -->, it would be:

if ( has_block( 'custom/block' ) ) {
   // ...
}
2
  • I found my problem why I asked this question: if ( has_block( 'core-embed/vimeo' ) || has_block( 'core-embed/youtube') || has_block( 'video' )) { // ... } I was placing youtube video and "has_block( 'video' )" doesn't recognises that.
    – Uģis
    Jan 15, 2019 at 14:38
  • Thanks for the extra info. In the example here above we assumed the video to be uploaded to the site and added via the wp:video block. To check if one has the wp:core-embed/youtube block one can use has_block( 'core-embed/youtube' ), To find the corresponding block type, one can switch to the code editor view with the Ctrl+Shift+Alt+M shortcut or via the settings.
    – birgire
    Jan 15, 2019 at 14:47

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.