Last active
October 23, 2020 09:10
-
-
Save milindmore22/02275bed6fb5d8752065626379c4cd09 to your computer and use it in GitHub Desktop.
Using AMP Script component for local storage.
This file contains hidden or 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
<?php | |
/** | |
* Local Storage Demo | |
* | |
* @requires AMP WordPress Plugin. | |
*/ | |
add_action( | |
'wp_head', | |
function() { | |
if ( ! is_amp_endpoint() ) { | |
return; | |
} | |
/** | |
* layout="nodisplay" will not execute script also adding height="0" will not work. | |
*/ | |
?> | |
<amp-script layout="fixed" script="local-store-demo" height="1" width="1"> | |
<div id="site-name" style="display:none;"> | |
<?php echo esc_html( get_bloginfo( 'name' ) ); ?> | |
</div> | |
<div id="site-info" style="display:none;"> | |
<?php | |
/** | |
* Retrives blog Info from predefined array. | |
* | |
* @return array blog info. | |
*/ | |
function bloginfo_array() { | |
$fields = array( 'name', 'description', 'wpurl', 'url', 'admin_email', 'charset', 'version', 'html_type', 'language' ); | |
$data = array(); | |
foreach ( $fields as $field ) { | |
$data[ $field ] = get_bloginfo( $field ); | |
} | |
return $data; | |
} | |
echo wp_json_encode( bloginfo_array() ); | |
?> | |
</div> | |
</amp-script> | |
<script id="local-store-demo" type="text/plain" target="amp-script"> | |
const testLocalStorage = () =>{ | |
const siteName = document.getElementById('site-name').textContent; | |
const siteInfo = document.getElementById('site-info').textContent; | |
localStorage.setItem('site-name', siteName); | |
localStorage.setItem('site-info', siteInfo); | |
console.log( localStorage.getItem('site-name') ); | |
console.log( localStorage.getItem('site-info') ); | |
} | |
testLocalStorage(); | |
</script> | |
<?php | |
} | |
); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment