获取此帖子的附件

时间:2012-01-20 16:29:15

标签: php wordpress

我有以下代码:

<?php

  include( 'includes/index.php' );
  get_header();

?>
  <section>
    <div class="text">
<?php

  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 />";
    endforeach;
    the_content();
  endwhile;

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

此代码位于page.php,默认情况下,我列出了一个帖子。我想只为该帖子query_posts('posts_per_page=1&cat=1');获取附件,现在它还获得该页面的附件。我该怎么办?此?

1 个答案:

答案 0 :(得分:0)

这是一个用于演示目的的简单示例。它显示了使用get_posts(类似于query_posts)来检索当前帖子的所有附件:

<ul>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post();    

 $args = array(
   'post_type' => 'attachment',
   'numberposts' => -1,
   'post_status' => null,
   'post_parent' => $post->ID
  );

  $attachments = get_posts( $args );
     if ( $attachments ) {
        foreach ( $attachments as $attachment ) {
           echo '<li>';
           echo wp_get_attachment_image( $attachment->ID, 'full' );
           echo '<p>';
           echo apply_filters( 'the_title', $attachment->post_title );
           echo '</p></li>';
          }
     }

 endwhile; endif; ?>
</ul>

来源:Codex: Display Images as a list