2013-10-24 28 views
2

我需要显示从我的WordPress主页上的约300个帖子只有1个随机文章。当我按刷新时,有时相同的帖子出现两次或很快在其他刷新后出现。我可以实现iTunes shuffle模式吗?我现在使用此代码:选择一个随机文章没有重复

<?php 
$args = array('numberposts' => 1, 'orderby' => 'rand'); 
$rand_posts = get_posts($args); 
foreach($rand_posts as $post) : 
?> 
<?php the_title(); ?> 
<?php endforeach; ?> 
+0

不错的问题,现在我有一个*真正的随机*代码来处理播放列表;) – brasofilo

回答

3

这只是一个概念证明,但应该把你放在正确的轨道上。重要提示:任何HTML输出发生之前

  • 我用饼干作为一个数组,也许它可以是一个逗号分隔的列表,并使用explode创建post__not_in
  • 阵列

    • 设置cookie一定会发生代码使用PHP 5.3+匿名函数,如果运行较低版本,则必须更改它
    • 如果没有设置cookie,您将不得不微调,很可能,我们需要做的就是再次运行get_posts而不需要not_in过滤器
    add_action('template_redirect', function() 
    { 
        # Not the front page, bail out 
        if(!is_front_page() || !is_home()) 
         return; 
    
        # Used in the_content 
        global $mypost; 
    
        # Set initial array and check cookie  
        $not_in = array(); 
        if(isset($_COOKIE['shuffle_posts'])) 
         $not_in = array_keys($_COOKIE['shuffle_posts']); 
    
        # Get posts 
        $args = array('numberposts' => 1, 'orderby' => 'rand', 'post__not_in' => $not_in); 
        $rand_posts = get_posts($args); 
    
        # All posts shown, reset cookie 
        if(!$rand_posts) 
        { 
         setcookie('shuffle_posts', '', time()-86400); 
         foreach($_COOKIE['shuffle_posts'] as $key => $value) 
         { 
          setcookie('shuffle_posts['.$key.']', '', time()-86400); 
          $id = 0; 
         } 
        } 
        # Increment cookie 
        else 
        { 
         setcookie('shuffle_posts['.$rand_posts[0]->ID.']', 'viewed', time()+86400); 
         $id = $rand_posts[0]->ID; 
        } 
        # Set the global, use at will (adjusting the 'bail out' above) 
        $mypost = $id; 
        return; 
    
        ## DEBUG ONLY 
        # Debug Results - remove the return above 
        echo 'current ID:' . $id . "<br />"; 
        if(!isset($_COOKIE['shuffle_posts'])) 
         echo 'no cookie set'; 
        else 
         var_dump($_COOKIE['shuffle_posts']); 
    
        die(); 
    }); 
    
    add_filter('the_content', function($content) 
    { 
        global $mypost; 
        if(isset($mypost)) 
         $content = '<h1>Random: ' . $mypost . '</h1>' . $content; 
        return $content; 
    }); 
    

    滤波器the_content仅仅是一个例子。 global $mypost可以在主题模板中的任何地方使用(在调整bail out之后)。

    如果与注册用户打交道,而不是cookie,我们可以将这些值存储在user_meta

  • +0

    Brasofilo,你是天才。我可以给你买一些好吃的咖啡吗? :) 我可以看到随机ID完全按照我的意愿。但是,我的Wordpress/Php知识很差。也许内容过滤器部分可以链接到模板部分或其他东西,所以我可以使用我的职位布局以外的函数文件? –

    +0

    是的,我在某处有一个捐赠链接;)不,“the_content”过滤器只是一个例子,任何地方都可以使用'global $ mypost'。 – brasofilo

    +0

    很好,再次感谢。我应该在哪里寻找那个捐赠链接? ;) –