How to get user ID during save_post
-
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’);
- The topic ‘How to get user ID during save_post’ is closed to new replies.