2013-10-24 9 views
2

내 Wordpress의 FrontPage에서 약 300 게시물의 무작위 게시물 하나만 표시해야합니다. 새로 고침을 누르면 같은 새로 고침이 두 번 또는 다른 새로 고침 직후에 나타납니다. iTunes 셔플 모드와 같은 것을 얻을 수 있습니까? 현재이 코드를 사용하고 있습니다.반복하지 않고 임의의 게시물 선택

<?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 출력은 내가 post__not_in

  • 의 배열을 만들 수 어쩌면 쉼표로 구분하고 explode을 사용할 수, 배열로 쿠키를 사용
  • 발생하기 전에

    • 쿠키를 설정하는 일이 있어야합니다 코드는 PHP 5.3+ 익명 함수를 사용합니다. 하위 버전을 실행하는 경우 변경해야합니다.
    • 쿠키가 설정되어 있지 않으면 조정할 필요가 있습니다. 없이 get_posts을 다시 실행해야합니다. 필터
    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을 조정 한 후).

    등록 된 사용자를 다루는 경우 쿠키 대신 user_meta에 값을 저장할 수 있습니다.

  • +0

    Brasofilo, 천재입니다. 내가 맛있는 커피 좀 사다 줄까? :) 내가 원하는대로 임의의 ID를 정확하게 볼 수 있습니다. 그러나, 내 워드 프레스/PHP 지식은 가난합니다. 어쩌면 콘텐츠 필터 부분이 템플릿 부분이나 다른 부분에 링크 될 수 있으므로 함수 파일 외부의 게시 레이아웃으로 작업 할 수 있습니까? –

    +0

    예, 어딘가에 기부 링크가 있습니다;) 아니요, 'the_content' 필터는 어디에서나'global $ mypost '를 사용하는 예입니다. – brasofilo

    +0

    좋습니다. 다시 한 번 감사드립니다. 그 기부 링크는 어디에서 찾아야합니까? ;) –

    관련 문제