Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'd like to run some code only if a gallery (inserted with the [gallery] 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?

share|improve this question
    
Normally that should be (no matter if it's working or not): $gallery = gallery_shortcode($post->ID) ? true : false; –  kaiser Jun 16 '11 at 23:38
add comment

2 Answers

up vote 11 down vote accepted

try :

if (strpos($post->post_content,'[gallery') === false){
  $gallery = 0;
}else{
  $gallery = 1;
}
share|improve this answer
2  
Just to make that (more) clear for later readers: 0 = false & 1 = true –  kaiser Jun 16 '11 at 23:37
    
Isn't it a kind of resource hog checking through lots of (probably) big texts for the occurence of [gallery ? –  vlood Jan 14 '12 at 16:23
2  
@vlood Strpos is the fastest function there is when it comes to searching strings and not big on resources so that's not an issue. –  Bainternet Jan 14 '12 at 18:36
    
I was thinking of comparing strpos with something on database side... If you got a website with lot's of visitors daily and for some reason you don't have caching enabled, filtering posts on the query might be a lot better than doing that in the php code. –  vlood Jan 22 '12 at 19:28
1  
Great, I added this to functions.php for re-use: function hasgallery(){global $post;return (strpos($post->post_content,'[gallery') !== false);} –  Mere Development Jul 26 '12 at 12:01
add comment

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();
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.