Randomise X最新的WordPress的帖子

问题描述:

我有下面的代码,它将显示来自定义的类别的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

您可以使用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