2013-10-03 106 views
0

首先 - 這是一個主要關於循環™的問題。我也有附件問題,但這是某種程度上的次要,因爲那裏有片段,我認爲可能是有用的。試圖從Wordpress循環中的帖子獲得附件,但獲取所有帖子的所有帖子

好了,這是要我想在頭版做:

  • 得到自定義後類型圖集「
  • 僅與第一個,得到一個特定附件7樓的帖子(在任何可能的方式,無論是文件名,在媒體管理器訂單...什麼是最好的,更乾淨的方式)
  • 與其他6,只是得到the_post_thumbnail()和多一點。

現在,我有這樣的:

<?php 
$args = array (
'post_type' => 'portfolio', 
'order' => 'DESC', 
'posts_per_page' => 7 
); 

$query = new WP_Query($args); 
$first_post = true; /* we will take the latest work first */ 
?> 

<?php if ($query->have_posts()) : ?> 
<?php while ($query->have_posts()) : $query->the_post(); ?> 

<?php 
if ($first_post): 
$first_post = false; 
?> 

    <div> /* This is the div for the first item */ 
      <?php /* let's take the first attachment */ 
      $args = array(
       'post_type' => 'attachment', 
       'numberposts' => 1, 
       'order' => 'DESC' 
       ); 

      $attachments = get_posts($args); 
      if ($attachments) : 
       foreach ($attachments as $attachment) : 
        echo wp_get_attachment_image($attachment->ID, 'full'); 
       endforeach; 
      endif; 
      ?> 
     </div> 
<?php else: ?> 
    /* Do something with the other 6 posts and their post_thumbnail */ 
<?php endif ?> 
<?php endwhile; ?> 

而現在的問題:

  • 首先:如果我設置 'numberposts' 所有(-1 )當試圖恢復附件,我從所有「組合」職位獲得所有附件。我不應該只與當前帖子(the_post())交​​互嗎?我不能完全理解循環的概念,這是主要問題。

  • 該代碼不會讓我成爲第一個附件,即使它被置於該帖子的媒體管理器中的第一位。

我應該去二級或嵌套循環?我已經閱讀並重新閱讀了代碼和其他教程,但仍然無法將其包圍。

非常感謝!

回答

0

用戶沙克蒂帕特爾給我的關鍵答案,但並沒有真正回答我有關環路的問題,所以這裏有雲:

的問題是與get_posts。它實際上運行並行查詢,而不考慮循環的當前步驟。所以我們必須要求它提供當前帖子的附件,因爲我們在循環中存儲在$post->ID之內。因此,瞭解這一點,我們有權要求第一附當前帖子是這樣的:

$args = array(
    'post_type' => 'attachment', 
    'posts_per_page' => 1, 
    'post_parent' => $post->ID, 
    'exclude'  => get_post_thumbnail_id() 
    ); 

$attachments = get_posts($args); 

我們指定哪些是我們不能從中會得到第一附後,並通過這種方式,而我們在它,排除帖子縮略圖。

我不知道這是否是最好的方式,因爲我們已經在一個循環,我們不應該需要一個新的查詢,我們不應該能夠檢索該附件沒有get_posts位?

無論如何,對get_posts更多信息(讀,而不是半睡眠狀態):http://codex.wordpress.org/Template_Tags/get_posts

0

使用此代碼:

$attachments = get_posts(array(
      'post_type' => 'attachment', 
      'posts_per_page' => -1, 
      'post_parent' => $post->ID, 
      'exclude'  => get_post_thumbnail_id() 
     )); 

     if ($attachments) { 
      foreach ($attachments as $attachment) { 
       $class = "post-attachment mime-" . sanitize_title($attachment->post_mime_type); 
       $thumbimg = wp_get_attachment_link($attachment->ID, 'thumbnail-size', true); 
       echo $thumbimg; 
      } 

     } 
+0

我不明白的第二部分,附件之一。這個塊有什麼作用? 我嘗試了第一部分,而不是-1我將它設置爲1,並且使用額外的post_parent和exclude參數,它完全符合我之前的操作,所以非常感謝! 不過,我並沒有把握循環的概念。爲什麼我必須使用post_parent?我沒有在任何給定的循環步驟中僅與當前帖子進行交互? – MrMerrick

+0

現在我再次考慮這個問題......可能是'get_posts()'從主查詢中獲取所有帖子,並且可能忽略當前循環步驟,這就是爲什麼需要'post_parent'? – MrMerrick

相關問題