• 0
    down vote
    favorite

    I’m trying to add a chatroom to our wordpress site. The company that we purchased the chatroom software from is doing a couple custom additions for us. For one of the additions they asked that we set a cookie to collect current user data.

    I apologize, I’m extremely new to PHP so please be gentle!

    For example, to collect User-ID number, I’ve tried adding this to our function.php file:

    $current_user = wp_get_current_user();
    
    add_action( 'init', 'my_setcookie' );
    function my_setcookie() {
       setcookie( 'id', $current_user->ID, 3 * DAYS_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
    }

    This is not producing anything when I look at the cookies being collected in my browser.

    This seems to be a very opaque topic, as I’ve not found much information about it online.

    Is there a way to set a cookie to collect current user data?

    Thank you!

Viewing 2 replies - 1 through 2 (of 2 total)
  • Are you able to set a cookie with an arbitrary name/value combination? if not, then you need to tweak some of those constants until you can set a cookie where you don’t have to use variable data.

    If you are able to set a cookie, but the value of ID is blank, then you may need to load $current_user inside your my_setcookie function. Just move that line inside the function.

    Are you seeing any errors in your log? You can turn on WP_DEBUG to get some information.

    You can add your own stuff to the error log by using the error_log function. This can be very useful for getting information about what’s going on. for example:

    error_log('Current user ID: ' . $current_user->ID');

    Will show you if you have a value for $current_user->ID

    Thread Starter tabithatomsin

    (@tabithatomsin)

    Thank you so much! This did it!

    add_action( 'init', 'my_setcookie_example' );
        function my_setcookie_example() {
      $current_user = wp_get_current_user();
       setcookie( 'id', $current_user->ID, 3 * DAYS_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
        }
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Set cookie in wordpress for current user info.’ is closed to new replies.