2012-06-15 61 views
0

我如何從特定頁面ID的所有子頁面檢索附件?如何從WordPress的特定頁面的子頁面檢索附件?

實施例:

特定頁面

  • 兒童(帶有附件)
  • 兒童(帶有附件)
  • 兒童(帶有附件)

我目前使用此代碼檢索網站範圍內的所有附件,但我想限制這只是從中拉圖像一個特定頁面的所有孩子。

<?php 
$args = array('post_type' => 'attachment', 'numberposts' => -1, 'post_status' => null, 'post_parent' => null); 
$attachments = get_posts($args); 
if ($attachments) { 
    foreach ($attachments as $post) { 
     setup_postdata($post); 
     the_title(); 
     the_attachment_link($post->ID, false); 
     the_excerpt(); 
    } 
} 
?> 

幾乎沒有使用此代碼按如下尼克的建議:

<?php 

$mypages = get_pages('child_of=19'); 
foreach ($mypages as $mypage ) { 
$attachments = get_children(array('post_parent' => $mypage->ID, 'numberposts' => 1, 'post_type' => 'attachment', 'post_mime_type' => 'image', 'orderby' => 'rand')); 


if ($attachments) { 

    foreach ($attachments as $post) { 

     setup_postdata($post); 
     the_title(); 
     the_attachment_link($post->ID, false); 
     the_excerpt(); 
    } 
} 
} 
?> 

然而,有兩個遺留問題:

  1. 限制的總照片拉量。使用'numberposts'只會限制從每個帖子中提取的圖像數量。隨機化。
  2. 隨機化。 Orderby => rand只會隨機化每個帖子中的圖像。我想隨機洗牌一切順序。
+0

爲防萬一我建議您將此問題移至WordPress網站,請訪問http://wordpress.stackexchange.com/ – leopic

回答

1

嘗試使用get_pages($args)

<?php $args = array(
'child_of' => 'SPECIFIC PAGE', 
'parent' => 'SPECIFIC PAGE', 
'post_type' => 'attachment', 
'post_status' => 'publish', 
'numberposts' => -1 
); ?> 

使用child_of將得到所有的孩子和孫子。

parent將限制這只是以此爲父母的孩子。沒有孫子。

查看此處瞭解更多詳情。 http://codex.wordpress.org/Function_Reference/get_pages

+0

@Joe,您可以將所有附件數據存儲在多維數組中[洗牌](http://php.net/manual/en/function.shuffle.php)。然後使用'for'循環顯示正確的附件數量。 – Nick

+0

只是好奇 - 這不會是拉動額外的未使用的數據(比如說有1000張圖片)?我認爲這是爲服務器做了大量浪費的工作? – Joe

+0

您已經在'get_children()'調用中從數據庫中提取數據。現在你只需要對它進行操作。而不是在foreach循環中輸出它,將它存儲在數組中。然後洗牌數組,然後通過數組循環輸出你想要的。是的,這是多一點工作,但我想不出從get_children()或get_pages()調用中獲得所需的方法。 – Nick

相關問題