これは概念実証にすぎませんが、正しい方向に進むはずです。重要事項:
- 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
。