• Resolved PeterC66

    (@peterc66)


    Thanks for the excellent plugin.

    I am trying to use some code from WPBeginner. It defines the same function in two different ways depending on whether a cookie is set or not. So logically the function cannot get declared twice. In essence the code is:

    function wpb_cookies_tutorial2() {
    	if(isset($_COOKIE['wpb_visit_time'])) {
    		function visitor_greeting() {}   
    	} else {
    		function visitor_greeting() {}   
    	}   
    }

    When I try to activate this I get:
    Snippet automatically deactivated due to an error on line 6: Cannot redeclare function visitor_greeting.

    If I try:

    function wpb_cookies_tutorial2() {
    	if(isset($_COOKIE['wpb_visit_time'])) {
    	if (!function_exists('visitor_greeting')){
    		function visitor_greeting() {}  }
    	} else {
    	if (!function_exists('visitor_greeting')){
    		function visitor_greeting() {}  }
    	}   
    }

    then Code Snippets accepts the code.

    Is that the best way to make it acceptable to Code Snippets?

    The page I need help with: [log in to see the link]

Viewing 1 replies (of 1 total)
  • Plugin Author Shea Bunge

    (@bungeshea)

    Hi @peterc66,

    The code you provided seems quite strange in its construction. In these situations, as in general with snippets, I’d recommend favouring anonymous functions over named functions.

    Here’s a rewritten version of that code:

    add_action(
    	'init',
    	function () {
    		$visit_time = gmdate( 'F j, Y g:i a' );
    
    		if ( isset( $_COOKIE['wpb_visit_time'] ) ) {
    			$last_visit = sanitize_text_field( wp_unslash( $_COOKIE['wpb_visit_time'] ) );
    
    			add_shortcode(
    				'greet_me',
    				function () use ( $last_visit ) {
    					$string = 'You last visited our website ' . esc_html( $last_visit ) . '. Check out what\'s new';
    					unset( $_COOKIE['wpb_visit_time'] );
    					return $string;
    				}
    			);
    
    		} else {
    			add_shortcode(
    				'greet_me',
    				function () {
    					return 'New here? Check out these resources…';
    				}
    			);
    		}
    
    		setcookie( 'wpb_visit_time', $visit_time, time() + 31556926 );
    	}
    );
Viewing 1 replies (of 1 total)
  • You must be logged in to reply to this topic.