Issue
I am working on a site where specific users are allowed front end creation of posts. I do this with WP User Frontend. I was wondering if there is a way to delete the previous post of a user, whenever they post a new one? I'm pretty comfortable with PHP, so hardcoding something to make this work is no problem.
Solution
An easy way to do this is to break up what you need to do in steps, and build your query from there.
Here are the steps I took:
- Create a loop of all posts that a user has under his/her name. This can be done by using the normal WP_Query functionality and using the Author arguments alongside the get_current_user_id() WordPress function.
- Create a counter which incremements at the end of your function
- Check the current state of the counter, and if it is not on the very first post, delete the post that it is on.
Here's the code that I put together. I've hooked the function onto admin_init
which could slow the backend down if you have A LOT of concurrent users, in which case it would probably be safer to just hook it into a post_save type action.
add_action( 'admin_init', 'removing_older_posts' );
function removing_older_posts() {
$args = array (
'post_type' => 'post',
'author' => get_current_user_id(),
'orderby' => 'date',
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) { //if the current user has posts under his/her name
$i = 0; //create post counter
while ( $query->have_posts() ) { //loop through each post
$query->the_post(); //get the current post
if ($i > 0) { //if you're not on the first post
wp_delete_post( $query->post->ID, true ); //delete the post
}
$i++; //increment the post counter
}
wp_reset_postdata();
}
}
Answered By - Frits Answer Checked By - Candace Johnson (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.