Home / functions.php / Check if post / page has a gallery
  • How to Check if post / page has a gallery

    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.

    wordpress snippet : PHP

    <>
    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.

    wordpress snippet : PHP

    <>
    echo get_post_gallery();
    

    ( WordPress codex functions, hooks, in this snippet. )

    post_gallery, get_post,
  • 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.