2015-02-06 57 views
-1

我有下面的代碼,它將顯示來自定義的類別的4個隨機帖子。但是,這有點過於隨意,我需要它顯示最近的4個,然後在每次刷新頁面時對其進行隨機化處理。Randomise X最新的WordPress的帖子

否則,我只是最終得到可以追溯到2年前的文章出現在主頁上。

<div class="article-block-v1"> 
<?php 
//get terms (category ids 11,2,33,34), then display one post in each term 
$taxonomy = 'category';// e.g. post_tag, category 
$param_type = 'category__in'; // e.g. tag__in, category__in 
$term_args=array(
    'include' => '1459', 
); 
$terms = get_terms($taxonomy,$term_args); 

if ($terms) { 
    foreach($terms as $term) { 
    $args=array(
     "$param_type" => array($term->term_id), 
     'post_type' => 'post', 
     'post_status' => 'publish', 
     'posts_per_page' => 4, 
     'orderby' => 'rand', 
    ); 
    $my_query = null; 
    $my_query = new WP_Query($args); 

    $i = 1; 

    if($my_query->have_posts()) { 
    echo '<ul>'; 
    while ($my_query->have_posts()) : $my_query->the_post(); ?> 

    <?php if ($i == 1): ?> 

    <div class="article-block-v1"> 

    <div class="category-label-large category-news-analysis"> 
     <a href="<?php the_permalink(); ?>"><p><?php echo $term->name; ?></p></a> 
    </div> 
    <div class="view2 third-effect"> 
    <?php the_post_thumbnail(); ?> 
     <div class="mask"> 
      <a href="<?php the_permalink() ?>" class="info" ><i class="fa fa-search"></i></a> 
     </div> 
    </div> 
    <ul class="homepagewhitebg"> 
     <li><h5><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h5></li> 
    </ul> 

    </div> 

    <?php else: ?> 

    <li><a href="<?php the_permalink(); ?>"><p><?php the_title(); ?></p></a></li> 

    <?php endif; ?> 

    <?php 
     $i++; 
      endwhile; 
      echo '</ul>'; 
     } 
     } 
    } 
    wp_reset_query(); // Restore global post data stomped by the_post(). 
?> 

演示1(4最近的) - 正則無需隨機的OrderBy
文章#1001
文章#1002
文章#1003
文章#1004

演示2(最近的4個 - 但隨機對這4個進行排序)
文章#1003
文章#1001
文章#1004
文章#1002


UPDATE 我現在也想這樣,但是它沒有考慮到我已經類別也不是隨機顯示的4個:

+0

您首先需要編寫一個查詢以返回4個最近的帖子。上面的代碼與問題並不相關。 – rnevius 2015-02-06 13:49:31

+0

好的,是的,我已經加入了我的嘗試,工作,但任何建議歡迎,因爲它仍然不是那裏。 – JordanC26 2015-02-06 14:21:08

回答

1

您可以使用shuffle()。在洗牌之前,你會想要得到4個最近的帖子(按順序)。很簡單,你可以這樣做以下:

// Get the 4 most recent posts 
$args = array('numberposts' => 4); 
$recent_posts = wp_get_recent_posts($args); 

// Shuffle them 
shuffle($recent_posts) 

foreach($recent_posts as $recent){ 
    // Do something with the $recent post 
} 

您可能需要通過額外的$args的功能,爲您的特定限制。

+0

好,是啊,認爲它正在通過,只是我希望的最後一件基本的事情,現在我將如何檢索foreach循環中的標題,縮略圖等。 我試過了:** echo $ recent-> post_title; **但沒有運氣。沒有輸出。 – JordanC26 2015-02-06 15:00:59

+0

默認情況下,[wp_get_recent_posts()](http://codex.wordpress.org/Function_Reference/wp_get_recent_posts)返回數組。您可以通過'$ recent [「post_title」]'來訪問標題。查看文檔以獲取更多信息:http://codex.wordpress.org/Function_Reference/wp_get_recent_posts – rnevius 2015-02-06 15:05:50

+0

現在,幾乎所有的東西都得到了,謝謝。有一件事,我想我需要使用:** get_the_category **函數,但是我怎麼能夠在使用** wp_get_recent_posts **的$ recent_posts循環中調用該類別呢? – JordanC26 2015-02-06 16:25:04