How to update post status to draft if user role is "pending'

I'm creating a website where user pays to publish posts. If this user membership expires, the role changes from "Subscriber" to "Pending".

I need a code that allows to update all posts to draft if certain user's role is "Pending" and then back to publish if is "Subscriber".

Any suggestions on this problem? I only found this plugin but it's not working.

Topic post-status Wordpress

Category Web


You should be able to use the set_user_role action which is triggered when a user's role is changed. The action function is passed the user's ID, new role, and old role(s). Something like this:

add_action( 'set_user_role', 'wpse161590_set_user_role', 10, 3 );
function wpse161590_set_user_role( $user_id, $role, $old_roles ) {
  if ( 'Pending' == $role ) {
    // set all of the user's posts to Draft
  }
  if ( 'Subscriber' == $role ) {
    // set all of the user's posts to Publish
  }
}

You may want to consider a custom post status on the off chance that a Subscriber has one or more posts manually set as Drafts when they are switched to Pending - to prevent those posts from being automatically published when the user renews and is switched back to Subscriber.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.