Skip to content
Advertisement

WordPress function get_post_gallery() does not register post’s gallery

I want to extract the images contained in a gallery block while maintaining their correct order. Since get_children() and get_attached_media() do not seem to register when the image order is changed in wp-admin, I’m trying to use get_post_gallery() instead.

My problem is that the function returns false, even though the post does have a gallery.

I tried both the example and the plain usage from Codex. Currently, my entire single.php looks like this:

<?php
get_header(); //html head etc
if (have_posts()): while (have_posts()) : the_post(); //the loop
    if ( get_post_gallery() ) :
    echo get_post_gallery();
else :
    echo (the_ID() . " has no gallery.");
endif; 
endwhile;
endif;  
?>

… which results in “ID has no gallery” every time.

However, the output of print_r($post->post_content); does include the following, which seems to confirm that there is in a fact a gallery:

<!-- wp:gallery {"ids":[80,81,82]} -->
<figure class="wp-block-gallery columns-3 is-cropped">
        <ul class ="blocks-gallery-grid">
        <!-- … --> 

I’m also attaching a screenshot from wp-admin to make sure I don’t misunderstand what constitutes a gallery. screenshot

Advertisement

Answer

get_post_gallery() works only for native galleries which have been created in classig WYSIWYG editor. You can find more about it there. Hovewer, if you create Gallery via Gutenberg, it create the whole HTML code instead of classic editor gallery which create shortcode like this: . Functions get_post_gallery(), get_post_galleries() and get_post_gallery_images() works only on classic galleries added via native shortcode.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement