Advertisement
Guest User

Untitled

a guest
Jul 20th, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. /**********************************************************
  2. * Use this script to set data in localStorage (client side)
  3. * this data will be available in client browser and you
  4. * can use it with javascript manipulation
  5. *
  6. * tags: wordpress, client side, localStorage, setItem
  7. *
  8. * by: Jeff Monteiro
  9. ***********************************************************/
  10.  
  11. /* Create a new blank js file into your repository */
  12.  
  13. data.js
  14.  
  15.  
  16.  
  17. /* Enqueue this file in wordpress */
  18.  
  19. function enqueue_my_scripts() {
  20.  
  21. $the_theme = wp_get_theme();
  22. $theme_version = $the_theme->get( 'Version' );
  23.  
  24. $js_version = $theme_version . '.' . filemtime(get_template_directory() . '/js/data.js');
  25. wp_enqueue_script( 'data', get_template_directory_uri() . '/js/data.js', array(), $js_version, true );
  26.  
  27. }
  28.  
  29. add_action( 'wp_enqueue_scripts', 'enqueue_my_scripts' );
  30.  
  31.  
  32.  
  33.  
  34. /* Create a function to add data into localStorage
  35. * @param data (array, key:value)
  36. * @param name (string)
  37. */
  38.  
  39. function add_my_data_to_localstorage( $data, $name ){
  40.  
  41. // Get current user id because data in browser needs to be personal
  42. $user_id = get_current_user_id();
  43.  
  44. // Test if user are logged in
  45. if( $user_id == null ){
  46. return;
  47. }
  48.  
  49. // Test if array is not empty
  50. if( !empty( $data ) && is_array( $data )){
  51.  
  52. // Encode to json
  53. $json = json_encode( $data );
  54.  
  55. // Now test if your data.js file is ready
  56. if( !wp_script_is( 'fit', 'done') ){
  57. wp_enqueue_script( 'fit' );
  58. }
  59.  
  60. // Create a inline script to put into data.js
  61. $script = "var data = ".$json."; localStorage.setItem('".$name."', JSON.stringify(data));";
  62. wp_add_inline_script( 'data', $script, 'before');
  63.  
  64. }
  65. else {
  66. return;
  67. }
  68. }
  69.  
  70.  
  71.  
  72. /* Final Steps */
  73. /* to get this working, you will to need initialize the function
  74. where you want, using a wordpress hook, filter or whatever */
  75.  
  76. // Create an array
  77. $data = array();
  78.  
  79. // Putting data into array
  80. $data["key"] = "value";
  81.  
  82. // Initialize
  83. add_my_data_to_localstorage( $data, 'mydata' );
  84.  
  85.  
  86. /* To manipuate data */
  87.  
  88. // In some JAVASCRIPT file
  89. var mydata = localStorage.getItem('mydata');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement