Check If Post / Page has a Gallery

Snippets by IsItWP

The WordPress gallery feature allows you to add multiple galleries attached as IDs in a single shortcode. You can search for the gallery shortcode in your WordPress post or page.

Instructions: Add the following code to the single.php file of your WordPress theme.

if ( get_post_gallery() ){
echo 'has gallery';
echo 'has no gallery';

After checking if the gallery exists, you may want to show the gallery. Simply replace echo 'has gallery'; in the above code with the following line.

echo get_post_gallery();

You may also enjoy adding limit to number of images in a gallery.

Comments   Leave a Reply

  1. i think is better…

    if ( get_post_gallery() ){
    echo ‘has gallery’;
    echo ‘has no gallery’;

    reference: https://codex.wordpress.org/Function_Reference/get_post_gallery

    1. Hi Just a Farax

      I agree, this snippet was posted before wp 3.6 when this was not an option. Ill update the snippet to reflect these changes thanks for the heads up.

  2. THANK YOU!!!!! Saved my life.

  3. <?php if (strpos($post->post_content,'[gallery’) === false){ ?>
    no gallery
    <? } else { ?>
    has gallery
    <?php } ?>

  4. How would you change this to go from php to html to php

    1. What you have above should work fine the other option would be to do the following.

      echo '<span class="className">html</span>';

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!