2017.11.22
単純にプラグインで実装可能です。
https://wordpress.org/plugins/last-viewed-posts/
プラグインをダウンロードしてきてlast_viewed_posts.phpを編集しましょう。主な設定項目は少ないのでザックリ解説していきます。
$zg_cookie_expire = 30; // After how many days should the cookie expire? Default is 360. $zg_number_of_posts = 4; // How many posts should be displayed in the list? Default is 10. $zg_recognize_pages = false; // Should pages to be recognized and listed? Default is true.
41行目あたりを上記のように設定。クッキーの保有期間を30日、一覧表示は4件、商品カテゴリのみを表示。という感じの設定になります。
function zg_lwp_header() { // Main function is called every time a page/post is being generated if (is_single()) { zg_lw_setcookie(); } else if (is_page()) { global $zg_recognize_pages; if ($zg_recognize_pages === true) { zg_lw_setcookie(); } } }
次に上記のコードを見つけます。47行目くらいにあるはずです。
これをWelcart用に書き換えます。
function zg_lwp_header() { // Main function is called every time a page/post is being generated if (is_single() && in_category('item')) { zg_lw_setcookie(); } else if (is_page()) { global $zg_recognize_pages; if ($zg_recognize_pages === true) { zg_lw_setcookie(); } } }
特に
if (is_single() && in_category(‘item’))
この箇所、最後のカッコが抜けるとエラーで動きませんので注意しましょう。最後に90行目くらいの出力場所を編集。
function zg_recently_viewed() { // Output echo '<ul class="viewed_posts">'; if (isset($_COOKIE["WP-LastViewedPosts"])) { //echo "Cookie was set.<br/>"; // For bugfixing - uncomment to see if cookie was set //echo $_COOKIE["WP-LastViewedPosts"]; // For bugfixing (cookie content) $zg_post_IDs = unserialize(preg_replace('!s:(\d+):"(.*?)";!e', "'s:'.strlen('$2').':\"$2\";'", stripslashes($_COOKIE["WP-LastViewedPosts"]))); // Read serialized array from cooke and unserialize it foreach ($zg_post_IDs as $value) { // Do output as long there are posts global $wpdb; $post = get_post($value);//Welcart用 $zg_get_title = $wpdb->get_results("SELECT post_title FROM $wpdb->posts WHERE ID = '$value+0' LIMIT 1"); foreach($zg_get_title as $zg_title_out) { echo "<li><a href=". get_permalink($value+0) . " title=". $zg_title_out->post_title . ">". usces_the_itemImage($number=0, $width=200, $height=200, $post, 'return'). "<span>". $zg_title_out->post_title. "</span></a></li>\n"; // Welcart 商品を出力 } } } else { //echo "No cookie found."; // For bugfixing - uncomment to see if cookie was not set } echo '</ul>'; }
商品個別ページのテンプレートに以下を書き加えて完了です。
<?php if (function_exists('zg_recently_viewed')): if (isset($_COOKIE["WP-LastViewedPosts"])) { ?> <h2>最近見た商品</h2> <?php zg_recently_viewed(); ?> <?php } endif; ?>