Wordpress Programming Tutorials, Guides & Best Practices
Explore 2+ expertly crafted wordpress tutorials, components, and code examples. Stay productive and build faster with proven implementation strategies and design patterns from DeveloperBreeze.
Adblocker Detected
It looks like you're using an adblocker. Our website relies on ads to keep running. Please consider disabling your adblocker to support us and access the content.
WordPress cheatsheet WordPress development template tags custom post types WordPress hooks shortcodes WordPress functions WordPress security WordPress themes WordPress plugins WordPress API WooCommerce WordPress customizer WordPress debugging WordPress CLI delete posts remove uploads custom PHP script wp_delete_post wp_delete_attachment
Code
php
How to Delete All WordPress Posts and Their Uploads Using a Custom PHP Script
<?php
// Load WordPress environment
require_once('/path/to/your/wp-load.php');
// Get all posts (any post type)
$args = array(
'post_type' => 'any', // 'any' retrieves all post types (posts, pages, custom post types)
'post_status' => 'any', // 'any' retrieves all post statuses
'posts_per_page' => -1, // Retrieve all posts
);
$all_posts = get_posts($args);
foreach ($all_posts as $post) {
// Get the post ID
$post_id = $post->ID;
// Check if the post has attachments (media files)
$attachments = get_attached_media('', $post_id);
// Delete each attachment associated with the post
foreach ($attachments as $attachment) {
$attachment_id = $attachment->ID;
// This deletes the file from the uploads directory and the database record
wp_delete_attachment($attachment_id, true);
}
// Delete the post itself
wp_delete_post($post_id, true); // true = force delete, bypass trash
}
echo 'All posts and their uploads have been deleted.';- Backup: Make sure you have a backup of your database and uploads folder before running this script.
- Use on a staging site: Test it on a staging environment before running on a live site, as it will permanently delete all posts and their uploads.
Oct 25, 2024
Read More Cheatsheet
php
WordPress Cheatsheet
- Loop through Posts:
if (have_posts()) :
while (have_posts()) : the_post();
// Loop content
endwhile;
endif;
Aug 20, 2024
Read More