How to set a cookie in wordpress?

Member

by daisha , in category: PHP CMS , 8 months ago

How to set a cookie in wordpress?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by ryleigh , 8 months ago

@daisha 

To set a cookie in WordPress, you can use the setcookie() function provided by PHP. Here's a step-by-step guide:

  1. Determine where you'd like to set the cookie. You can do this in your theme's functions.php file or in a custom plugin.
  2. Decide what information you want to store in the cookie. For example, if you want to remember a user's name, you might use the following code:
1
2
3
4
5
function set_user_name_cookie() {
    $user_name = "John Doe";
    setcookie( 'user_name', $user_name, time() + 86400, COOKIEPATH, COOKIE_DOMAIN );
}
add_action( 'init', 'set_user_name_cookie' );


  1. In the above code, the setcookie() function takes several parameters: a. The first parameter is the name of the cookie (user_name in this example). b. The second parameter is the value of the cookie ($user_name in this example). c. The third parameter is the expiration time of the cookie. In this example, it is set to expire in 24 hours (86400 seconds). d. The fourth parameter is the path on your website where the cookie will be available. Using COOKIEPATH ensures that the cookie will be available throughout your site. e. The fifth parameter is the domain of your website. Using COOKIE_DOMAIN will make the cookie available on all subdomains as well.
  2. The set_user_name_cookie() function is hooked to the init action using the add_action() function. This ensures that the cookie will be set when WordPress initializes.
  3. Customize the code as per your requirement, such as changing the cookie name, value, and expiration time.
  4. Save the modified file, and the cookie will now be set when users visit your website.


Remember to consider the privacy and security implications of setting cookies, especially when dealing with sensitive user data.