How can i use my own (custom) session value in WordPress?
For example: $_SESSION['myname']="4lvin"
I’ve already inserted session_start()
at all page i need as following.
<?php
session_start();
$_SESSION['myname'] = "4lvin";
?>
But not working Global-wise.
Just working on the self page.
It is NOT call-able Globally from another pages (using same logic).
EDIT: “THE PLUGIN BELOW ISN’T AVAILABLE ANYMORE, SO PLEASE USE THAT PLUGIN INSTEAD: WordPress Session Plugin“
There is a good WordPress Plugin adapted from CodeIgniter Session class: WP Sessions Plugin.
When you activate the plugin, you can start to use
$session
object from anywhere in your theme ($session
object as long as global). For instance, to use $session object intoheader.php
file, simply add this code:Here is some useful functions for both theme and plugin developers.
You can add session data like this:
To retrieve session data:
To get all session data:
To remove one item from session:
To remove more items from session:
You can also use Flashdata which is session data that will only be available for the next server request, are then automatically cleared. These can be very useful when you use them for informational or status messages (e.g. âProduct has been deletedâ).
To destroy session:
The plugin also supports shortcodes. You can print any session data on your posts or pages:
To reach second key:
I hope this helps for someone.
WordPress doesn’t use sessions, that’s why your session variables aren’t working.
As a matter of fact, if certain variables are defined, WordPress will actually destroy
$_SESSION
to keep itself stateless.But if you really want to use sessions, try adding
session_start()
at the beginning of yourwp-config.php
file. This will (hopefully) start sessions whenever WP starts up, so you’ll then be able to set and read your$_SESSION
variables elsewhere in the system.One simple solution without using plug-in or without modifying the
wp-config.php
is to update your theme’sfunctions.php
and insert at the very beginning the following:Since the
functions.php
(or so called theme functions file) is a template included in WordPress themes automatically and acts like a plugin for your WordPress site. Moreover, if you have more than 1 theme installed on your website, modifying thefunctions.php
will affect only the chosen theme, not all (where you may not want to enable sessions).WordPress does support it.
You need to add following lines at the top of
functions.php