Code to auto expire posts after 30 days

There are some issues with your query

$daystogo = "30";

$sql =
"UPDATE {$wpdb->posts}
SET post_status="draft"
WHERE (post_type="post" AND post_status="publish")
AND DATEDIFF(NOW(), post_date) > %d";

$wpdb->query( $wpdb->prepare( $sql, $daystogo ) );

You do not want to untrash trashed posts by declaring them as draft, right? And you really do not want to make every automated saved version (post_status = inherit) a draft. So only select published posts.

Use $wpdb-prepare() for EVERY query.

(Edit: Every query that has variable inputs, that is. Don’t use prepare for entirely static queries that have no variable inputs.)

Use the WPDB class variables instead of the plain table name $wpdb->posts instead of wp_posts. See the Codex.

Test your query first before code them. Use something like an MySQL frontend or MySQL-Admin. In your sql-query, there is a ) at the end where no one should be.

Leave a Comment