Search code examples
phpwordpressif-statementcookiesshortcode

setcookie() needs to manually reload the page to work


I have setup a cookie that hides a particular shortcode content. I am using a URL (http://www.yourwebsite.com/?EmailSubscriber=true) to trigger the cookie and to set it to "true". The particular code is working fine except that it needs to be reloaded for the condition to take effect.

Here is my code

if ($_GET['EmailSubscriber'] == 'true') {
    setcookie('EmailSubscriber', 'true', time() + (86400 * 30 * 6), "/");
} 

these are the shortcodes I've made

function EmailSubscriber_function( $atts, $content = null ) {
    $atts = shortcode_atts(
        array(
            'class' => '',
        ), $atts, 'EmailSubscriber' );  

        if(isset($_COOKIE['EmailSubscriber'])) {
            return '<div id="emailSubscriber" style="padding:20px 0;"><div class="darkSec"><div class="cck tve_clearfix tve_empty_dropzone">' . do_shortcode($content) . '</div></div></div>';
        }
}
add_shortcode( 'EmailSubscriber', 'EmailSubscriber_function' );

function EmailSubscriber_function( $atts, $content = null ) {
    $atts = shortcode_atts(
        array(
            'class' => '',
        ), $atts, 'EmailSubscriber' );  

        if(isset($_COOKIE['EmailSubscriber'])) {
            return '<div id="emailSubscriber" style="padding:20px 0;"><div class="darkSec"><div class="cck tve_clearfix tve_empty_dropzone">' . do_shortcode($content) . '</div></div></div>';
        }
}
add_shortcode( 'EmailSubscriber', 'EmailSubscriber_function' );

All I need is if I input this URL http://www.yourwebsite.com/?EmailSubscriber=true then when the page loads first time it triggers the condition and show/hide the necessary contents.


Solution

  • If you want to use cookie immediately, you can use also sessions for checks or just save your cookie manually:

    if ($_GET['EmailSubscriber'] == 'true') {
        setcookie('EmailSubscriber', 'true', time() + (86400 * 30 * 6), "/");
        $_COOKIE["EmailSubscriber"] = 'true';
    }
    

    By this operation $_COOKIE["EmailSubscriber"] = 'true'; you will not save cookie really, but your scripts will think, that you do this.