Instantly share code, notes, and snippets.
octalmage/cookie_sidebar.php Secret
Last active
March 26, 2023 11:20
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
<?php | |
/* | |
Plugin Name: WP Shortcode Example | |
Description: It's a shortcode! | |
Version: 0.1.0 | |
Author: Sally | |
*/ | |
function cookie_sidebar() { | |
ob_start(); | |
?> | |
<div id="cookie_sidebar"> | |
Loading... | |
</div> | |
<button id="setCookieButton">Set Cookie</button> | |
<!-- TODO: This JavaScript should be in a seperate file. --> | |
<script type="text/javascript"> | |
var ajax_url = "<?= admin_url( 'admin-ajax.php' ); ?>"; | |
jQuery.post(ajax_url, { 'action': 'cookie_sidebar_pick' }, function(response) { | |
jQuery('#cookie_sidebar').html(response); | |
}); | |
jQuery('#setCookieButton').on('click', function() { | |
createCookie('preferredMember', 'true'); | |
alert('cookie set!'); | |
}); | |
function createCookie(name, value, days) { | |
var expires = ""; | |
if (days) { | |
var date = new Date(); | |
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); | |
expires = "; expires=" + date.toUTCString(); | |
} | |
document.cookie = name + "=" + value + expires + "; path=/"; | |
} | |
</script> | |
<?php | |
return ob_get_clean(); | |
} | |
add_shortcode( 'cookie_sidebar', 'cookie_sidebar' ); | |
function cookie_sidebar_pick() { | |
// TODO: This HTML should be pulled from another file. | |
$sidebar1 = <<<EOT | |
<div id="sidebar1" class="hide"> | |
Welcome preferred member! | |
<img src="https://unsplash.it/600/200.png"> | |
</div> | |
EOT; | |
$sidebar2 = <<<EOT | |
<div id="sidebar2" class="hide"> | |
Welcome, please consider signing up! | |
<img src="https://unsplash.it/600/210.png"> | |
</div> | |
EOT; | |
if ( $_COOKIE['preferredMember'] === 'true' ) { | |
echo $sidebar1; | |
} else { | |
echo $sidebar2; | |
} | |
wp_die(); | |
} | |
add_action( 'wp_ajax_nopriv_cookie_sidebar_pick', 'cookie_sidebar_pick' ); | |
add_action( 'wp_ajax_cookie_sidebar_pick', 'cookie_sidebar_pick' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment