2

Wordpress のフロントページに約 300 件の投稿からランダムに 1 つだけ表示する必要があります。更新を押すと、同じ投稿が2回表示されるか、他の更新の直後に表示されることがあります。iTunes シャッフル モードのようなものを実現できますか? 私は現時点でこのコードを使用しています:

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

1 に答える 1

3

これは概念実証にすぎませんが、正しい方向に進むはずです。重要事項:

  • HTML出力が発生する前にCookieを設定する必要があります
  • 私はクッキーを配列として使用しました。おそらくそれはコンマ区切りのリストでありexplode、配列の作成に使用できますpost__not_in
  • コードは 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

于 2013-10-24T19:20:03.613 に答える