2013-10-24 27 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

    很好,再次感謝。我應該在哪裏尋找那個捐贈鏈接? ;) –