Using Sessions in WordPress
When needing to take a custom shopping cart and checkout solution and tie it into WordPress. We needed to have thousands of unique products available within the custom WordPress and have a customer’s name and cart total visible within the top header.
I searched the whole source code of this great piece of blogging software, for the popular phrase session_start(). I was noticing sessions working when this was added but the values were not the same.
So I started searching Google for a fix of my problem. I found a lot of people asking the same question: “Why don’t sessions work in WordPress?” Finally I found a solution to fix this little issue and guess what, it is a simple one.
The Solution
The only thing you have to do is call session_start(); before any output is sent to the client. Now you might think: Nice, but what happens when I upgrade my WordPress installation to the latest version? Well, yes, your changes will be lost. That is the reason why we first should think of where to add these changes.
Normally upgrading your installation will replace all files, except one. Yes, it is the wp-config.php file. Even better, there isn’t any output to a client when this file is loaded during the WordPress execution. The prefect solution when thinking about future WordPress updates.
Let’s get started add the next lines of code to our wp-config.php file:
// Make the use of sessions possible.
if (!session_id())
session_name('xyz');
session_start();
… and sessions are enabled on your blog! I added the session_name to help with making sure the server is collecting the correct set of information within your browser. I think the best place to add these lines is at the top of the wp-config.php file, immediately after the php starting tag “<?php”
I hope this will help you out when facing the same problem.
![[Return to HOME] web design solutions](/images/logo_body.jpg)