X

Check if post / page has a gallery

Adding this snippet to your wordpress theme will let you check to see if a post contains the gallery shortcode. Add this code to the single.php template of your wordpress theme inside the loop.



Code Snippet:


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

If you want to show the gallery after you check if one exists replace echo ‘has gallery’ with the following code.


Code Snippet:


echo get_post_gallery();

Comments  Leave a Reply

  1. i think is better…

    if ( get_post_gallery() ){
    echo ‘has gallery’;
    }else{
    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!