Trusted WordPress tutorials, when you need them most.
Beginner’s Guide to WordPress
WPBカップ
25 Million+
Websites using our plugins
16+
Years of WordPress experience
3000+
WordPress tutorials
by experts

WordPressのCookieを設定、取得、削除する方法(プロ並みに)

編集メモ: WPBeginner のパートナーリンクから手数料を得ています。手数料は編集者の意見や評価に影響を与えません。編集プロセスについて詳しく知る。

WordPressサイトでCookieを使用する方法を知りたいですか?

Cookieは、ユーザーのブラウザーに一時的な情報を保存する便利なツールです。この情報を利用して、パーソナライゼーションや行動ターゲティングを通じてユーザー体験を向上させることができます。

この究極のガイドでは、WordPress Cookieをプロのように設定、取得、削除する方法を紹介します。

How to set, get, and delete cookies in WordPress

注:このチュートリアルは上級者向けです。HTML、CSS、WordPressサイト、PHPを十分に理解していることが必要です。

Cookieとは?

Cookieとは、ユーザーがサイトを訪問した際にブラウザーに作成・保存されるプレーンテキストファイルのことです。Cookieを使用して、WordPressサイトにさまざまな機能を追加することができます。

Cookieの一般的な使用例を紹介します:

  • ユーザーのログイン情報の保存と管理
  • ユーザー訪問中の一時的なセッション情報の保存
  • ユーザーがeコマースストアを訪問中にお買い物カゴの項目を記憶する
  • パーソナライズされたユーザー体験を提供するためのサイト上でのユーザーアクティビティのトラッキング

お分かりのように、Cookieはサイトオーナーにとって非常に便利なツールですが、少々侵略的でもあります。メールマーケティンググロースハック、そしてオンラインマーケティング全体における最近の傾向では、サイトがビーコンとして機能するCookieを設定することができ、サイト間でユーザーの活動を保存し、共有するために使用することもできます。

そのため、欧州連合(EU)はEU Cookie法を制定し、サイト所有者が情報を保存するためにCookieを使用していることを宣言する必要があります。

GDPR/CCPAのためにCookieポップアップを追加する方法のガイドで、自分のサイトでこれを行う方法を学ぶことができます。

一般的なWordPressサイトでのCookieの使われ方

初期設定では、WordPressはログイン中のユーザーセッションと認証を管理し、コメントフォームに記入したユーザーの名前とメールアドレスを記憶するためにCookieを使用します。

ただし、サイト上のWordPressプラグインの多くは、独自のCookieを設定することもあります。

例えば、OptinMonsterでは、新規訪問者と再訪問者に異なるメールオプトインフォームを表示することができ、Cookieを使用することでこれを実現しています。

Googleアナリティクスや Google Adsenseのような外部のウェブサービスをサイトで利用している場合、それらのサービスもサードパーティのCookieをサイトに設定することがあります。

ブラウザー設定で、すべてのサイトCookieを表示できます。例えばGoogle Chromeの場合、まず「設定」ページを開いてください。

右上の「3つの点」アイコンをクリックして「設定」を選択するか、アドレスバーにchrome://settingsと入力してください。

Content settings in Google Chrome

設定ページで、「コンテンツ設定」を検索する必要があります。

コンテンツ設定」で「Cookie」をクリックします。

Cookies section in Chrome settings

Cookieの設定ページが開きます。

次に、「すべてのCookieとサイトデータを見る」オプションをクリックする必要があります。

View all cookies and site data

次のページでは、訪問したすべてのサイトがブラウザーに保存したすべてのCookieとサイトデータのリストが表示されます。

検索ボックスにサイトのアドレスを入力すると、そのサイトが保存しているデータが表示される。

View site cookies

個別項目をクリックすると、個々のCookieとそのコンテンツの詳細が表示されます。

WordPressでCookieを設定する方法

このチュートリアルに従うには、テーマのfunctions.phpファイルにコードを追加するか、WPCodeなどのコードスニペットプラグインを使用する必要があります。この作業を行ったことがない場合は、WordPressでコードスニペットをコピー&ペーストする方法をご覧ください。

まず、PHPsetcookie()関数を使用します。この関数は、以下のパラメータを受け取ります:

  • Cookie名
  • Cookieの値
  • Expire – オプション。Cookieの有効期限を設定します。
  • パス – オプション。初期設定ではサイトのルートが使用されます。
  • Domain – オプションで、初期設定ではあなたのサイトのドメインを使用します。
  • Secure – オプションで、true の場合のみ Cookie データを HTTPS 経由で転送します。
  • httponly – オプション。true に設定すると、Cookie は HTTP 経由でのみアクセスでき、スクリプトからは使用できません。

では、WordPressサイトにコード・スニペットを追加してみましょう。このコードは、ユーザーがサイトを訪れた正確なタイムスタンプをCookieに保存します:

function wpb_cookies_tutorial1() { 

$visit_time = date('F j, Y  g:i a');

if(!isset($_COOKIE[wpb_visit_time])) {

// set a cookie for 1 year
setcookie('wpb_visit_time', $visit_time, time()+31556926);

}

} 

サイトにアクセスし、ブラウザーCookieを確認してください。wpb_visit_timeという名前のCookieが見つかります。

WordPressでCookieを取得して使用する方法

ユーザーのブラウザーに1年間保存されるCookieを作成したので、この情報をサイトでどのように利用できるか見てみましょう。

Cookieの名前がわかれば、PHPのどこでも$_COOKIE[]変数を使って簡単に呼び出すことができます。Cookieを設定するだけでなく、Cookieを使ってサイトで何かをするコードを追加してみましょう:

function wpb_cookies_tutorial2() {
// Time of user's visit
$visit_time = date('F j, Y g:i a');

// Check if cookie is already set
if(isset($_COOKIE['wpb_visit_time'])) {

// Do this if cookie is set
function visitor_greeting() {

// Use information stored in the cookie
$lastvisit = $_COOKIE['wpb_visit_time'];

$string .= 'You last visited our website '. $lastvisit .'. Check out whats new'; 

return $string;
}	

} else { 

// Do this if the cookie doesn't exist
function visitor_greeting() {
$string .= 'New here? Check out these resources...' ;
return $string;
}	

// Set the cookie
setcookie('wpb_visit_time',  $visit_time, time()+31556926);
}

// Add a shortcode
add_shortcode('greet_me', 'visitor_greeting');

}
add_action('init', 'wpb_cookies_tutorial2');

各パーツが何をするかを示すために、コード内でコメントしています。このコードはCookieに保存された情報を使用し、ショートコードを使って出力します。

サイト上の任意の場所にショートコード[greet_me]を追加し、ユーザーが最後に訪問した日時を表示できるようになりました。

あなたのサイトにとってより便利になるよう、自由にコードを変更してください。例えば、リピーターユーザーには最近の投稿を、新規ユーザーには人気の投稿表示することができます。

WordPressでCookieを削除する

ここまでで、Cookieを設定し、それを後でサイトで使用する方法を学びました。次に、Cookieを削除する方法を見てみましょう。

Cookieを削除するには、コードに以下の行を追加する必要があります:

unset($_COOKIE['wpb_visit_time']);

wpb_visit_timeを削除しようとしているCookieの名前に置き換えることを忘れないでください。

上で使ったのと同じサンプル・コードを使って、このコードをいくつかの文脈に当てはめてみましょう。今回は、Cookie を削除し、新しい情報で再び設定します:

function wpb_cookies_tutorial2() {
// Time of user's visit
$visit_time = date('F j, Y g:i a');

// Check if cookie is already set
if(isset($_COOKIE['wpb_visit_time'])) {

// Do this if cookie is set
function visitor_greeting() {

// Use information stored in the cookie
$lastvisit = $_COOKIE['wpb_visit_time'];

$string .= 'You last visited our website '. $lastvisit .'. Check out whats new'; 

// Delete the old cookie so that we can set it again with updated time
unset($_COOKIE['wpb_visit_time']); 

return $string;
}	

} else {
// Do this if the cookie doesn't exist
function visitor_greeting() {
$string .= 'New here? Check out these resources...' ;
return $string;
}
}
add_shortcode('greet_me', 'visitor_greeting');

// Set or Reset the cookie
setcookie('wpb_visit_time',  $visit_time, time()+31556926);
}
add_action('init', 'wpb_cookies_tutorial2');

ご覧のように、このコードでは、内部に保存された情報を使用した後、Cookieを削除しています。後で、更新された時間情報でCookieを再びセットします。

WordPressでCookieを使用するためのエキスパートガイド

WordPressのCookieを設定、取得、削除するためにコードを使用する方法がわかったところで、WordPressでCookieを使用することに関連する他のガイドをご覧になりたいかもしれません。

この投稿がWordPress Cookieを簡単に設定、取得、削除する方法を学ぶのにお役に立てば幸いです。また、WordPressの一般的なエラーとその修正方法に関するガイド、およびWordPressユーザーに最適な分析ソリューションのエキスパートピックもご覧ください。

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

情報開示 私たちのコンテンツは読者支援型です。これは、あなたが私たちのリンクの一部をクリックした場合、私たちはコミッションを得ることができることを意味します。 WPBeginnerの資金源 をご覧ください。3$編集プロセスをご覧ください。

Avatar

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience in WordPress, Web Hosting, eCommerce, SEO, and Marketing. Started in 2009, WPBeginner is now the largest free WordPress resource site in the industry and is often referred to as the Wikipedia for WordPress.

究極のWordPressツールキット

ツールキットへの無料アクセス - すべてのプロフェッショナルが持つべきWordPress関連製品とリソースのコレクション!

Reader Interactions

19件のコメント返信を残す

  1. Syed Balkhi says

    Hey WPBeginner readers,
    Did you know you can win exciting prizes by commenting on WPBeginner?
    Every month, our top blog commenters will win HUGE rewards, including premium WordPress plugin licenses and cash prizes.
    You can get more details about the contest from here.
    Start sharing your thoughts below to stand a chance to win!

  2. Alan Brady says

    A very useful and informative article, thank you.
    I found that just using unset didn’t seem to delete the cookie, I had to set the cookie expiry time to sometime in the past, e.g.:
    setcookie(‘wpb_visit_time’, $visit_time, time()-1);

  3. Debbie Kurth says

    Problem is, when I implement code like this, I get an warning error and the cookie fails, when in wordpress.

    Warning: Cannot modify header information – headers already sent by (output started

    How do you go around that?

  4. Nigel says

    Thanks for the awesome tutorial!

    A small mistake: In the first code snippet $wpb_visit_time should be ‘wpb_visit_time’

  5. Matt says

    Hi there, you seem to have an error in your code for the first example:

    function wpb_cookies_tutorial1() {
    $visit_time = date(‘F j, Y g:i a’);
    if(!isset($_COOKIE[$wpb_visit_time])) {
    // set a cookie for 1 year
    setcookie(‘wpb_visit_time’, $current_time, time()+31556926);
    }
    }

    You specify the variable as $visit_time but in the setcookie function you call $current_time.

    Thank for the guide(s) though they are super useful.

    • WPBeginner Support says

      Thanks for pointing that out, we will be sure to update and fix that, glad our guides have been useful :)

      管理者

  6. Anastasia says

    Your articles are really helpful but I need to understand the codings very well so I want to know,
    Do I have to copy and paste all the code displayed here?
    Do I replace wbp_visit_time, wbp_cookies_tutorial with the name of my site?

  7. Brian says

    I don’t know why anytime I try to search my website using any search engines it writes website not trusted
    What’s wrong? How can My website be trusted by all browsers and search engines?

  8. Geeby says

    Apologies for resurrecting this thread but i need some help.
    The first page of my site asks customers to select their region. The products available will differ depending on where they choose.
    I don’t want them to have to re-select this location every time they go to the homepage.
    Any advice?

    • WPBeginner Support says

      You would want to check with the support for your eCommerce plugin for if they have a method to set that for your users.

      管理者

  9. Les says

    Great article. You said to put the code in the functions.php file. I am using WP Elementor, I only need the cookie values pulled up when a user goes to a certain page. Can this code be added on a specific page? I want to create the cookie with certain values that come from a form, the first time the user completes the form. After that, the next time they come back to this page, the form should auto populate from the cookie data., this reduces the fields they need to complete on a return visit.

    • WPBeginner Support says

      For that, you would want to reach out to the form plugin you are using for if they have a system for that already set up.

      管理者

    • Anthony Coffey says

      You can add the code to functions.php and use the WordPress function “is_page()” to add conditional logic to your cookie code snippet.

      The is_page() function accepts either page ID, slug or name/title. It’s pretty easy to use, you can read more about the is_page() function online in the WordPress codex.

返信を残す

コメントありがとうございます。すべてのコメントは私たちのコメントポリシーに従ってモデレートされ、あなたのメールアドレスが公開されることはありませんのでご留意ください。名前欄にキーワードを使用しないでください。個人的で有意義な会話をしましょう。