I have the following code:

      while (have_posts()) : the_post();
          if(get_the_title() == 'Archive') query_posts('posts_per_page=1&cat=1');
          $category = get_the_category();
          if ($category[0]->name) echo '<h1>'.$category[0]->name.'</h1>';

           $attachments = get_children( array('post_parent' => get_the_ID(), 'post_type' => 'attachment', 'post_mime_type' =>'image') );
           foreach ( $attachments as $attachment_id => $attachment ): 
           $image = wp_get_attachment_url( $attachment_id, 'medium' );
            echo $image."<br />";

      <?php edit_post_link('Click here in order to edit this page'); ?>
        </div><!--END /.text-->

This code is in page.php where by default I list a post.I want to get the attachements only for that post query_posts('posts_per_page=1&cat=1'); now it also get the attachements for the page., how can I do this?

2 Answers 2


Try this using the get_children function:

global $post;
$args = array(
    'numberposts' => -1,
    'order'=> 'ASC',
    'post_mime_type' => 'image',
    'post_parent' => $post->ID,
    'post_status' => 'any',
    'post_type' => 'attachment'
$attachments = get_children($args);

Reference: http://codex.wordpress.org/Function_Reference/get_children


what i understood from your code is, you are trying to get the attachment from the particular post,

it can be easily done using query_post,

query_posts( 'attachment_id=5' )

where '5' is the post ID

  • Well it's not that easy because I don't know the id since i'm querying to display that post
    – Uffo
    Commented Jan 20, 2012 at 17:42
  • 1
    then get the post id first, $pID = get_the_id(); query_posts( "attachment_id='$pID'" ); Commented Jan 20, 2012 at 17:52
  • query_posts should only be used on the main query. Use a new WP_Query object instead. Commented Jul 23, 2012 at 19:07

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.