Selectively applying action based on role

I’ve added an action to my functions.php file that forces a plugin (Content Scheduler) to act on posts, even when it wasn’t explicitly enabled by the person writing the post.

I’ve got that working, but I want it to work only when the author’s role is one that I’ve specified, and better yet, work differently for different roles. The role-checking code isn’t working. I’m attempting to call the “user_has_role” function (which I am calling successfully elsewhere in the same file, so I know that part should work), but either it is not working in this context, or it is not getting called at all.

function user_has_role( $roles_to_check=array() ) {
  if( ! $roles_to_check ) return FALSE;
  global $current_user;
  get_currentuserinfo();
  $user_id = intval( $current_user->ID );
  if( ! $user_id ) { return FALSE; }
  $user = new WP_User( $user_id ); 
  return in_array( $roles_to_check, $user->roles, FALSE );
}

function my_function($post_id, $post) {
    $is_role1 = user_has_role( array('role1') );
    $is_role2 = user_has_role( array('role2') );
    if ($is_role1) { $flag = 1; }
    if ($is_role2) { $flag = 2; }
    if ($flag != null) {        
    // do Content Scheduler stuff
    }
}

add_action( 'save_post', 'my_function', 10, 2);

Thanks in advance.

0

Leave a Comment