Sunday, April 5, 2015

Delete Wordpress Posts / Pages With IXR Client

Sometimes we want to delete many pages in Wordpress. Doing so manually can be time consuming, so here is how to do it with a simple PHP script.

Technical Details
  • PHP Version PHP 5.5.11 (cli) (built: Apr  8 2014 15:07:14)
  • Wordpress 4.1.1
  • protocol between PHP script and Wordpress: IXR XML-RPC version 1.7.4 7th September 2010. This library is available in Wordpress source code in /wp-includes directory, and also available in Incutio website http://scripts.incutio.com/xmlrpc/
What the script do:
  • Get last 200 posts ID from the website
  • Delete them all
At th moment I cannot get more than 200 posts in a single 'wp.getPosts'. So if we need to delete more than 200 pages we need to call 'wp.getPosts' a few times

<?php

/**
 * Delete all articles in a Wordpress website with XML-RPC
 */
 
/* Ideas from
  http://djzone.im/2011/04/simple-xml-rpc-client-to-wordpress-made-easy/
  http://codex.wordpress.org/XML-RPC_WordPress_API
 */

require("class-IXR.php");   // from Wordpress

$USER = 'username';
$PASS = 'password';

// Delete all posting 
// limited to 200 posts each run

if (1) {
    $client = new IXR_Client('http://yourwordpressadress.com/xmlrpc.php');
    $post_id = 1;
    $filter["number"] = 200;
    /* $filter[] can have some parameters as follows:
     *  struct filter: Optional.

      string post_type
      string post_status
      int number
      int offset
      string orderby
      string order
     */

    if (!$client->query('wp.getPosts', $post_id, $USER, $PASS, $filter)) {
        echo('Error occured during getting post.'
        . $client->getErrorCode() . ":" . $client->getErrorMessage());
    }

    $post = $client->getResponse();
    foreach ($post as $key => $item) {
        printf("key:%d %d\n", $key, $item["post_id"]);
        $post_id = $item["post_id"];
        $content['post_id'] = $post_id;
        $delete_status = $client->query('wp.deletePost', 1, $USER, $PASS, $post_id);
        printf("delete status: %d\n", $delete_status);
        if ($delete_status == 0)
            echo('Error occured during getting post.'
            . $client->getErrorCode() . ":" . $client->getErrorMessage()) . "\n";
    }
}
?>
?>

Next to do: displaying pretty code with http://ajblk.github.io/SyntaxHighlightGenerator-v3.0/OnlineGenerator.html

Reference:

1 comment:


  1. Hello,

    we provide affordable and result-oriented SEO services, please give a chance to serve you.


    Thanks
    Admin: E07.net

    ReplyDelete