How to Set Post Status to Draft if older than today

In a previous question I needed to set a future dated post (custom post type) as published on save instead of scheduling it.

On the date it’s ‘scheduled’ for I’d like to set it as a draft again. I’ve been trying to hook into init and wrap it in an if checking for post type. I figured it would compare to server time and then set status to draft if it was older than server time.

Read More

As a rough outline:

if custom post type
  get_the_time of post
  get the server time
  if post time is older than server time set status to draft
endif

Here and update with some code I’m working with.

function sfn_show_expire(){
    global $wpdb;
    $server_time = date('mdy');
    $result = $wpdb->get_results("SELECT * FROM wp_posts WHERE post_type = 'show' AND post_status = 'publish'");
    if( !empty($result)) foreach ($result as $a){
        $show_time = get_the_time('mdy', $a->ID );
        if ( $server_time > $show_time){
            $my_post = array();
            $my_post['ID'] = $a->ID;
            $my_post['post_status'] = 'draft';
            wp_update_post( $my_post );
        }
    } // end foreach
}
add_action( 'init', 'sfn_show_expire' );

It’s getting the posts I need and is giving me the server time but isn’t doing anything past that as far as I can tell.

Related posts

Leave a Reply

2 comments

  1. Your query isn’t giving you a post ID, it’s giving you an entire post. The SELECT * returns all columns, ID, post_status, etc. So setting $my_post['ID'] = $a doesn’t do anything for you in this case.

    Try using: $my_post['id'] = $a->ID; instead. That should accurately set your ID before you call wp_update_post() and you should be in business.

    Aside from that, I see no problems with what you’re doing … except that querying the database every time the site is loaded might eventually create performance issues. I’d set up an hourly chron job instead to automate the process … then it doesn’t depend on or slow down user traffic.

  2. I wanted to comment but looks like your post is closed for comment.

    Anyway, be very careful, my friend, to leave the declaration of array OUTSIDE of the loop:

    $my_post = array();
    

    otherwise, your script will use excessive memory and never finish for large database!

    Let me know if any questions