Skip to content

Instantly share code, notes, and snippets.

@benrolfe
Last active December 10, 2021 13:26
Show Gist options
  • Save benrolfe/6e91111c028e222428d0e11711a584a7 to your computer and use it in GitHub Desktop.
Save benrolfe/6e91111c028e222428d0e11711a584a7 to your computer and use it in GitHub Desktop.
Create / Delete / Check cookies
add_action( 'wp', 'action_cookies' );
function action_cookies() {
global $post;
// abort if not a page/post
if(! $post)
{
return;
}
// list of page slugs to protect (must have same format as below)
$protected_slugs = [
'1-reveal',
];
// default page that user is redirected to after subscribing
$default_protected_slug = '1-reveal';
// "success" page after subscribing to set cookie
$cookie_create_page_slug = 'cookie-create';
// page to delete cookies (for testing purposes only)
$cookie_delete_page_slug = 'cookie-delete';
// cookie actions >>>
if( $post->post_name === $cookie_create_page_slug ) {
// set cookie to expire in 10 years
setcookie( 'manna-anglican-subscribed', TRUE, time() + ( 10 * 365 * 24 * 60 * 60 ) );
// redirect to protected page
$slug = ( isset( $_COOKIE['manna-anglican-page-requested'] ) ? $_COOKIE['manna-anglican-page-requested'] : $default_protected_slug );
wp_redirect( get_permalink( get_page_by_path( $slug ) ) );
exit;
} else if( $post->post_name === $cookie_delete_page_slug ) {
// delete cookies (for testing purposes only)
setcookie( 'manna-anglican-subscribed', null, time() - 3600 );
setcookie( 'manna-anglican-page-requested', null, time() - 3600 );
} else if( in_array( $post->post_name, $protected_slugs ) ) {
// prevent access to protected pages
if( ! isset( $_COOKIE['manna-anglican-subscribed'] ) ) {
// set cookie to expire in 1 day
setcookie( 'manna-anglican-page-requested', $post->post_name, time() + ( 24 * 60 * 60 ) );
// convert "1-reveal” to "1-sign-up”
$subscribe_page_slug = str_replace('-reveal', '-sign-up', $post->post_name );
// redirect to page to allow user to subscribe
wp_redirect( get_permalink( get_page_by_path( $subscribe_page_slug ) ) ); exit;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment