Skip to content

Instantly share code, notes, and snippets.

@fwolf
Created July 5, 2010 17:14
Show Gist options
  • Save fwolf/464533 to your computer and use it in GitHub Desktop.
Save fwolf/464533 to your computer and use it in GitHub Desktop.
Find and recover un-continous id of WordPress post.
<?php
/**
* Find and recover un-continous id of WordPress post.
*
* Will make empty draft using these id for edit them later.
* Also change revision or auto-draft to draft.
*
* @package fwolfweb
* @subpackage wordpress
* @copyright Copyright 2010, Fwolf
* @author Fwolf <fwolf.aide+fwolfweb.wordpress@gmail.com>
* @since 2010-07-05
*/
require_once('wp-config.php');
// Connect db
$conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db(DB_NAME, $conn);
if (defined('DB_CHARSET'))
mysql_set_charset(DB_CHARSET);
// Table prefix
if (!isset($table_prefix))
$table_prefix = 'wp_';
// Any revision or auto-draft in db ?
$sql = "UPDATE {$table_prefix}posts set post_status = 'draft' WHERE post_status = 'revision'";
mysql_query($sql, $conn);
$i = mysql_affected_rows($conn);
if (0 < $i)
echo "Converted $i revision to draft.<br />\n";
$sql = "UPDATE {$table_prefix}posts set post_status = 'draft' WHERE post_status = 'auto-draft'";
mysql_query($sql, $conn);
$i = mysql_affected_rows($conn);
if (0 < $i)
echo "Converted $i auto-draft to draft.<br />\n";
// Got all id of posts
$sql = "SELECT id FROM {$table_prefix}posts ORDER BY id ASC";
$rs = mysql_query($sql, $conn);
$i = mysql_affected_rows($conn);
if (0 < $i) {
// Have posts, continue traversal all rows.
$ar_missed = array();
$i_row = 1;
while ($row = mysql_fetch_assoc($rs)) {
if ($i_row < $row['id']) {
// Got missed id, add to array
for ($j = $i_row; $j < $row['id']; $j++)
$ar_missed[] = $j;
$i_row = $row['id'];
}
$i_row ++;
}
// There are missed id ?
if (0 < count($ar_missed)) {
foreach ($ar_missed as $id) {
$sql = "INSERT INTO {$table_prefix}posts
(id, post_title, post_status, post_type) VALUES
($id, '$id', 'draft', 'post')";
mysql_query($sql, $conn);
}
echo 'Inserted id: ' . implode(', ', $ar_missed)
. " as draft.<br />\n";
}
}
// Close db
mysql_close($conn);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment