PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, July 8, 2022

[FIXED] How to delete all previous posts by user, whenever they create a new one

 July 08, 2022     php, posts, wordpress     No comments   

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:

  1. 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.
  2. Create a counter which incremements at the end of your function
  3. 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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing