wordpress snippets last updated   : April 22, 2014
we now have 631 snippets

Check if post / page has a gallery

wordpress snippet

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.

snippet :  PHPcopy
if ( get_post_gallery() ){
echo 'has gallery';
}else{
echo 'has no gallery';
}
source →

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

snippet :  PHPcopy
echo get_post_gallery();
source →
  • pete

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

    • http://wpsnipp.com Kevin Chard

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

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

  • pete

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

  • DG

    THANK YOU!!!!! Saved my life.

  • just a farax

    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

    • http://wpsnipp.com Kevin Chard

      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.

jqsnipp.com | we just launched jquery snippets website