WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] How to get user ID during save_post (4 posts)

  1. adhocracy
    Member
    Posted 2 years ago #

    Hi everyone,

    I am writing a plug-in that will automatically add two categories and set the featured image of a post based on the author/current user.

    Everything works except getting the user ID. For some reason it is always 0 or empty. I have tried everything I can think off and nearly worn Google out! Any assistance would be greatly appreciated.

    I have tried this code in functions.php and in a custom plugin. I cant get it to work.

    Thanks,

    Steve

    Here's my code.

    // add categories to blog post on save
    // based on author/current user
    function set_my_categories($post_ID){

    // don't add categories if post exists

    if(wp_is_post_autosave($post_ID) || wp_is_post_revision($post_ID)) {
    return $post_ID;
    }

    // THIS BIT DOES NOT SEEM TO WORK
    $current_user = wp_get_current_user();

    echo("Author ID: ");
    echo($current_user->user_id);

    // All good from here once $current_user->user_id is populated (which is isn't)!

    // add correct categories to post based on author
    // this is used to filter the correct blogs by author
    // insert featured image into post
    // this is a preloaded image from the gallery.

    if($current_user->user_id == 1){ // admin
    $author_category = 14; // steve
    $author_thumbnail = 721; // steve's image
    }
    elseif($current_user->user_id == 18){ // lisa
    $author_category = 4; // lisa
    $author_thumbnail = 527; // lisa's image
    }
    else{
    $author_category = 0;
    $author_thumbnail = 0;
    }

    if($author_category != 0){
    wp_set_post_categories( $post_ID, array(5, $author_category) );
    set_post_thumbnail($post_ID, $author_thumbnail);
    }
    }
    add_action('save_post', 'set_my_categories');

  2. bcworkz
    Member
    Posted 2 years ago #

    Try using $current_user->ID instead of $current_user->user_id.

  3. adhocracy
    Member
    Posted 2 years ago #

    Thanks bcworkz, just tried it but it doesn't work. Either. $current_user appears to be empty inside the function.

    If I put 'echo($current_user->ID)' outside the function it works.

    I am stumped on this one.

    Any other ideas?

  4. adhocracy
    Member
    Posted 2 years ago #

    Very strange.

    It now works. Perhaps I am going mad.

    $current_user->ID + a server restart did it.

    Thanks everyone.

Topic Closed

This topic has been closed to new replies.

About this Topic