2013-02-20 66 views
0

首先,我花了最後一週的時間,並將這些代碼從多個不同的來源組合在一起,如果您將從我遇到的示例中獲得一個真正的frankenstein。我不擅長編寫PHP,但迄今爲止做了很多。任何投入將不勝感激。循環後的數組隨機結果

我正在研究一個項目,在該項目中我需要從貓4的所有子類別中獲取最新的10個結果,之後我期待隨機化結果並顯示。我見過很多使用shuffle()的例子;功能,但我有問題正確實施它。

這裏是我的代碼:

<?php 

$categories = get_categories('child_of=4'); 
    foreach($categories as $category) { 
    $args=array(
    'showposts' => 10, 
    'category__in' => array($category->term_id), 
    'caller_get_posts'=>1 
); 
$posts=get_posts($args); 
    shuffle($posts); 
    if ($posts) { 
    foreach($posts as $post) { 
     setup_postdata($post); ?> 
     <div <?php post_class('boxy');?>> 
     <a href="<?php the_permalink() ?>"><?php the_post_thumbnail(); ?></a> 

    <?php the_content(''); ?> 
    </div> 
     <?php 
    } 
    } 
} 
?> 

鏈接到我這裏結果:Live work in progress在每個類別

此代碼是隨機的結果,而是按類別顯示他們.. 我希望我已經明確足以應付看起來像是一個簡單的問題。

感謝

回答

1

你需要讓所有職位的陣列首先與你有所有類別。比你需要洗牌一樣。試試這個,

$posts = array(); 
$categories = get_categories('child_of=4'); 
foreach($categories as $category) { 
    $args=array(
    'showposts' => 10, 
    'category__in' => array($category->term_id), 
    'caller_get_posts'=>1 
    ); 
$posts = $posts + get_posts($args); 
} // Close your foreach here 

....比你的代碼,因爲它是...

+0

工作就像一個魅力,只需要將'showposts'的數量更改爲一個更高的數字,因爲是隻顯示10個結果總計 – StephenPerrett 2013-02-21 22:00:57

+0

嗯,我添加了一個新的兒童貓,應該顯示與此代碼廣告我遇到麻煩它來顯示。我剪掉了孩子,並能夠通過特定的帖子類型的貓ID顯示他們,但嘗試後,我仍然無法確定爲什麼新的貓不會與其他人一起顯示.. – StephenPerrett 2013-02-24 20:27:39

0
$categories = get_categories('child_of=4'); 
$cats = array(); 
foreach($categories as $category) { 
    $cats[] = $category->term_id; 
} 

$args=array(
    'showposts' => 10, 
    'category__in' => $cats, 
    'orderby' => 'rand', 
    'caller_get_posts'=>1 
); 
$posts=get_posts($args); 

我希望這將是一個更有效的解決方案。我沒有測試過它。