Last active
July 9, 2019 14:08
-
-
Save jeffsmonteiro/6aa08ad3110eda74da6e4ad251477d15 to your computer and use it in GitHub Desktop.
WordPress Snippet - Putting data in browser localStorage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/********************************************************** | |
* Use this script to set data in localStorage (client side) | |
* this data will be available in client browser and you | |
* can use it with javascript manipulation | |
* | |
* tags: wordpress, client side, localStorage, setItem | |
* | |
* by: Jeff Monteiro | |
***********************************************************/ | |
/* Create a new blank js file into your repository */ | |
data.js | |
/* Enqueue this file in wordpress */ | |
function enqueue_my_scripts() { | |
$the_theme = wp_get_theme(); | |
$theme_version = $the_theme->get( 'Version' ); | |
$js_version = $theme_version . '.' . filemtime(get_template_directory() . '/js/data.js'); | |
wp_enqueue_script( 'data', get_template_directory_uri() . '/js/data.js', array(), $js_version, true ); | |
} | |
add_action( 'wp_enqueue_scripts', 'enqueue_my_scripts' ); | |
/* Create a function to add data into localStorage | |
* @param data (array, key:value) | |
* @param name (string) | |
*/ | |
function add_my_data_to_localstorage( $data, $name ){ | |
// Get current user id because data in browser needs to be personal | |
$user_id = get_current_user_id(); | |
// Test if user are logged in | |
if( $user_id == null ){ | |
return; | |
} | |
// Test if array is not empty | |
if( !empty( $data ) && is_array( $data )){ | |
// Encode to json | |
$json = json_encode( $data ); | |
// Now test if your data.js file is ready | |
if( !wp_script_is( 'fit', 'done') ){ | |
wp_enqueue_script( 'fit' ); | |
} | |
// Create a inline script to put into data.js | |
$script = "var data = ".$json."; localStorage.setItem('".$name."', JSON.stringify(data));"; | |
wp_add_inline_script( 'data', $script, 'before'); | |
} | |
else { | |
return; | |
} | |
} | |
/* Final Steps */ | |
/* to get this working, you will to need initialize the function | |
where you want, using a wordpress hook, filter or whatever */ | |
// Create an array | |
$data = array(); | |
// Putting data into array | |
$data["key"] = "value"; | |
// Initialize | |
add_my_data_to_localstorage( $data, 'mydata' ); | |
/* To manipuate data */ | |
// In some JAVASCRIPT file | |
var mydata = localStorage.getItem('mydata'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment