Check if post/page has gallery?

I’d like to run some code only if a gallery (inserted with the shortcode) has been inserted into a post/page. I did the following:

gallery_shortcode($post->ID) ?
$gallery = 1 : $gallery = 0;

However, this always sets $gallery = 0 whether there’s a gallery or not. Am I using this incorrectly?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

try :

if (strpos($post->post_content,'[gallery') === false){
  $gallery = 0;
}else{
  $gallery = 1;
}

Method 2

My iteration on the suggested solution here, is the following function in my theme’s functions.php:

function has_gallery($post_id = false) {
    if (!$post_id) {
        global $post;
    } else {
        $post = get_post($post_id);
    }
    return ( strpos($post->post_content,'[gallery') !== false); 
}

Which I can then call in a template file (doesn’t care about The Loop):

$has_gallery = has_gallery($post_id) ? true : false;

or more direct:

has_gallery($post_id); //will evaluate to true/false

$post_id is optional, the following will only work within The Loop:

has_gallery();

Method 3

How about simply using the get_post_gallery() function. This is exactly the way, most themes are checking if a post has a gallery to print the correct body CSS classes:

if ( get_post_gallery() ) {
    // run your code in here
}

P.S. I really don’t like solutions that search the whole content for anything, even if string functions are typically quite fast in PHP, it’s still a huge performance overhead.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x