Reputation: 1661
I have members site where users have to pay to subscribe. When user subscribe his role becomes "member" and now can publish to custom post type called "user-profile"
what I want to do is change the status of all published posts to pending in this post type if for example the user role changed to "expired"
I tried this, but doesn't seem to have any effect
function auto_expire_posts(){
global $wpdb, $wp_roles;
//get all post ids of published posts.
$post_ids = $wpdb->get_results( "SELECT * FROM $wpdb->posts WHERE post_status = 'publish' ");
foreach($post_ids as $id){
$postid = $id->ID;
if ($_GET['role'] == "expired" )
{
$profile_post = array();
$profile_post['ID'] = $postid;
$profile_post['post_status'] = 'pending';
// Update the post into the database
wp_update_post( $profile_post );
}
}
}
add_action('set_user_role', 'auto_expire_posts');
Upvotes: 3
Views: 2058
Reputation: 26160
Fundamentally, your function should have expired all posts. Functionally, it works, so when you say "no effect", that is surprising.
Your function should be modified per below, in order to be more efficient (you don't need to loop over the posts) and to ensure you only update the relevant posts, as well as ensuring it doesn't throw notices.
Revised code:
// This action passes 3 parameters, so let's accept them - $user_id, $new_role, $old_roles
function auto_expire_posts( $user_id, $new_role, $old_roles ) {
// If the user didn't USED to be a member, then no need to do anything
if ( ! in_array( 'member', $old_roles ) ) {
return;
}
global $wpdb;
// Set the array of values to update
$update = array(
'post_status' => 'expired'
);
// Set the array that defines the "WHERE" clause
// WHERE is ONLY published posts that are authored by the specified user
$where = array(
'post_status' => 'publish',
'post_author' => $user_id
);
// $updated will contain the number of posts changed
$updated = $wpdb->update( $wpdb->posts, $update, $where );
}
// Ensure the add_action passes the 3 parameters through (10 is the priority, 3 is the number of parameters)
add_action( 'set_user_role', 'auto_expire_posts', 10, 3 );
This is tested, and I have proven that it works. However there are a handful of reasons you may find it does NOT do what you want:
do_action('set_user_role')
that is core WordPress. This hook may not be called depending on how you are changing the user's role. This hook does get called if you go to the user's profile through the dashboard, change the role, and click "Save User". If it doesn't work, be sure to explain exactly how you are changing the roles.Upvotes: 3