Steamer Lane Studio技術備忘録ワードプレス

WordPress cookieを使った閲覧履歴

wordpress WordPress cookieを使った閲覧履歴
最終更新日: 2023年4月15日

時流からするとcookieは使われない傾向にあるが、ポータルサイト案件で「閲覧履歴」ってことになったので調べてやってみた。 single.phpに記述、テンプレの先頭に記述すること。 <?php
global $history;
//register cookie
if(is_single()&& in_category(array(2)) ){//機能を使い抽出するカテゴリをID記述
//if has cookie
if( isset($_COOKIE['history']) ){
//explode
$history = explode(",", $_COOKIE['history']);
//if has ID
$have = in_array($post->ID, $history);
//true
if($have == true){
//erase here ID
$history = array_diff($history,array($post->ID));
$history = array_values($history);
}
//cookie count>=5 to trim 4
if(count($history) >= 10 ){//このコードで登録するcookieは10件だよ
$set_history = array_slice($history , 0, );
}else{
$set_history = $history;
}
//register cookie
$register = $post->ID.','.implode(",", $set_history);
setcookie( 'history', $register, time() + 7776000,'/');//cookieは一か月期限だよ
//cookies has not here ID
}else{
$register = $post->ID;
setcookie( 'history', $register, time() + 7776000,'/');
}
//not post the cookie read only
}else{
if( isset($_COOKIE['history']) ){
$history = explode(",", $_COOKIE['history']);
}
}
?>

閲覧履歴を表示するコード、モジュールphpにしてinc/下に置いて必要なテンプレで呼び出すのがいいかな。
<?php
global $history;
if (isset($_COOKIE['history'])) {
$history = explode(",", $_COOKIE['history']);
}
?>
<?php
global $history;
//if has history(cookie)
if (!empty($history)){
$args = array(
'posts_per_page' => 3,//取得表示件数singleに書いたcookieの保存件数より多くなると?
'post__in' => $history,
'orderby' => 'post__in',
);
$the_query = new WP_Query($args);
if ( $the_query->have_posts() ) :
?>

<div class="seenEntries cnt<?php $the_query = new WP_Query( $args );$post_count = $the_query->post_count;echo $post_count;?>">//div入れ子のクラスに表示数を当ててる
<?php while ( $the_query->have_posts() ) : $the_query->the_post();?>
<div>
<a href="<?php echo get_permalink(); ?>">
<picture>
<img src="<?php the_post_thumbnail_url('thumbnail');?>" alt="<?php echo get_the_title(); ?>">
</picture>
<h3>
<span><?php the_field('kana'); ?></span>//左記はここで作ったACFのフィールド呼び出しだから消す
<?php echo get_the_title(); ?>
</h3>
</a>
<?php the_tags( '<p class="tagsWrap">', '</p>' ); ?>//tag を表示させる場合→tag searchのテンプレと併せると回遊構造ができる。その件別掲かな。
&lt/div>
<?php endwhile;?>

<?php endif;wp_reset_postdata();}else{ ?>
<?php get_template_part('inc/recommend'); ?>//閲覧履歴のcookieが無かったら「お奨め」のブロックを表示する様にしたのでなければ空欄でOK
<?php } ?>