0

I am trying to make a notification function for a user's account dashboard that displays if they have not added any images to their profile's gallery. I found this page, which is a function that checks if the CURRENT page has any attachments: Check if post/page has gallery?

How can I change that to check by a specific post ID, i.e. a function that will check if post 2 has a gallery or not?

1
  • 1
    the code you linked checks if the post content contains the gallery shortcode, which is not the same as checking if a post has any attached images. a post can have attached images without containing the gallery shortcode. please clarify which you want to check for.
    – Milo
    Commented Sep 22, 2012 at 17:21

2 Answers 2

1
$args = array(
    'post_type' => 'attachment',
    'numberposts' => null,
    'post_status' => null,
    'post_parent' => $post_id
);
$attachments = get_posts($args);
if ($attachments) {
    echo "attachments rock!";
    }
}

If you want to make sure the atachements are an image, you would use:

if ( $attachments and wp_attachment_is_image( $post_id ) ) {
echo "attachments rock!";
}
2
  • Thanks for the reply, I am not getting the proper result on this.Here is what I put in : function gallerycheck_func(){ $args = array( 'post_type' => 'attachment', 'numberposts' => null, 'post_status' => null, 'post_parent' => 2 ); $attachments = get_posts($args); if ( $attachments and wp_attachment_is_image( 2 ) ) {echo '<p style="text-align:center;">Your profile looks good!</p>';}else{ echo '<p style="text-align:center;">You need to add atleast one photo to your profile!</p>'; }} add_shortcode( 'gallerycheck', 'gallerycheck_func' );
    – Kyle
    Commented Sep 22, 2012 at 20:44
  • Okay it worked perfectly with just the top part, thanks! It was the and wp_attachment_is_image( $post_id ) which seems to be misfiring. Thanks for your help!
    – Kyle
    Commented Sep 22, 2012 at 20:55
0

According to that question you mentioned, you need to the have the post content in order to check if there is a gallery assigned to it. The function get_post is what you need.

$my_post = get_post($some_post_id);
if (strpos($my_post->post_content,'[gallery') === false){
  $gallery = 0;
}else{
  $gallery = 1;
}
2
  • Thanks for the reply, I am not sure if this will work because I don't actually use the [gallery] shortcode in my page template? I tried this, but wasn't getting a result
    – Kyle
    Commented Sep 22, 2012 at 20:49
  • like Milo pointed out above, I misspoke stating I was checking for the shortcode, I should have said I was checking if their were images IN the gallery, thanks you anyway
    – Kyle
    Commented Sep 22, 2012 at 20:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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