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 have added a custom field to the image attachement. When this custom field is checked the image will be part of a carousel on the home page. Now i am able to get the custom field to work and save the selected value, but how do i query the database so only the post with the custom field checked will be selected and their parent post.

In the end i want a shortcode with output like:

<a href="link-to-permalink-post"><img alt="attachment-title" src="img-src-link"/></a>
<div class="caption"><p>attachment-title</p></div>

I think in need to use get_post_meta but how??

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted
<?php
$args = array( 'post_type' => 'attachment',***'meta_key'=>'your meta key','meta_value'=>'your meta value',*** 'numberposts' => -1, 'post_status' => null, 'post_parent' => $post->ID ); 
$attachments = get_posts($args);
if ($attachments) {
    foreach ( $attachments as $attachment ) {
        echo apply_filters( 'the_title' , $attachment->post_title );
        the_attachment_link( $attachment->ID , false );
    }
}
?>
share|improve this answer
    
ah almost there, i see however the meta-value is stored like a:2:{i:0;s:0:"";i:1;s:20:"in-carousel-homepage";} can this be the cause your solution doesn't work? –  alex Mar 26 '12 at 11:10
    
ah turned out i had this custom field saved as array, but it wasn't neccesary. So i saved just a single value. –  alex Mar 26 '12 at 11:19
    
do you know how i get the permalink of the attachment parent ? <a href="'. get_permalink($post->ID).'"><img alt="'.$attachment->post_title.'" permalink didn't work –  alex Mar 27 '12 at 11:32
1  
@alex $post->ID would not work, as $post will be overridden when you use get_posts with $attachments = get_posts($args); and loop it, so first you assing your post id to another varaible like $parent_post_id = $post->id and then go for attachment loop and then use get_permalink($parent_post_id)... –  Rajeev Vyas Mar 27 '12 at 13:32
    
tx Rajeev, but i overlooked one thing. In my case i want to have the permalink to the post the image is original attached to. At the moment all images in my carousel point to TEST. Test is the title of my test page with carousel shortcode. –  alex Mar 27 '12 at 14:14
show 1 more 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.