v2 Documentation
Data Stores
At some point in developing a WordPress theme you’ll need to store some text or a simple array in one place and then use it in another. With Data Stores you can store data temporarily over a page load, in a user’s cookie, or permanently in the database.
Database
Variables work great over the course of a request's lifecycle but sometimes you may need to store simple data more long term. In these instances, WPM offers a database store.
To set a db store:
// string
wpm('store.db')->set('background_color', '#cecece');
// boolean
wpm('store.db')->set('display_sidebar', true);
// integer
wpm('store.db')->set('default_banner_image', 182);
// simple array
wpm('store.db')->set('social_channel_urls', [
'twitter' => 'http://twitter.com',
'facebook' => 'http://facebook.com'
]);
WPM uses serialization to store information in the database.
To recall any database store:
// echo
echo wpm('store.db')->get('background_color');
// return
$social_urls = wpm('store.db')->get('social_channel_urls');
You can check to see if the database has a variable with the has
method.
if(wpm('store.database')->has('social_channel_urls')) {
// do something because 'social_channel_urls' are stored
}
Forgot what you called it? Grab everything to take a look:
dd(wpm('store.db')->all());
The dd function is a great little helper for debugging.
Warning
Be careful of database find/replace statements as this may corrupt serialized data.
Variables
With variables, you can store data temporarily during a page load. As a example, you may want to set a title in you template file, like an alternate title, and display it in the header.
WordPress uses global variables heavily but they can quickly muddy your global namespace. Instead, throw them in WPM and fish them out when you need them.
To set a variable:
// string
wpm('store.var')->set('alt_title', 'About The Team');
// boolean
wpm('store.var')->set('show_sidebar', true);
// integer
wpm('store.var')->set('banner_image_id', 182);
// array
wpm('store.var')->set('alert', [
'type' => 'danger',
'title' => 'Do not press the button!'
]);
Anything that can be stored as a variable can be stored as in WPM. To recall any variable:
// echo
echo wpm('store.var')->get('alt_title');
// return
$alert = wpm('store.var')->get('alert');
You can check to see if the variable exists with the has
method.
if(wpm('store.var')->has('alt_title')) {
// do something because 'alt_title' are stored
}
Forgot what you called it? Grab everything to take a look:
dd(wpm('store.var')->all());
The dd function is a great little helper for debugging.