WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] How to send a cookie to the browser. (3 posts)

  1. adrian7
    Member
    Posted 2 years ago #

    Ok, so I have the code :

    function set_my_cookie(){
    setcookie('my_cookie', '2011', 8600, '/', get_bloginfo('url')); //set the cookie
    }

    This is attached as a hook to wp_head add_action('wp_head', 'set_my_cookie'); .

    It doesn't works since wp_head() is called after some output is sent to the bowser and I am supposed to set the cookie BEFORE any output is sent.

    So what hook can I use to make it work?

  2. adrian7
    Member
    Posted 2 years ago #

    ***edit***
    I also need the current post ID (if is_single) to be available for my function.

  3. adrian7
    Member
    Posted 2 years ago #

    Good news I finally figured a way out. Heredown the code:

    add_action('posts_results', 'set_my_cookie');
    function set_my_cookie(){
       global $wp_query;
    
       $cpost = $wp_query->posts[0]; //get the current post
    
       if(!wp_is_post_revision($cpost)) {
          if( is_single() || is_page() ) {
              $id = $cpost->ID;
                   setcookie('my_cookie_for_'.$id, '2011', 8600, '/', get_bloginfo('url')); //set the cookie
    
           }
       }
    }

Topic Closed

This topic has been closed to new replies.

About this Topic