How to automatically change a posts status to draft based on custom field

Written by  on October 6, 2016 

I would like to set a post to Draft automatically based on a custom field date.

Note: I am using the plugin Magic Fields. ^(

Based on the following code I want to use a custom field ‘expiration’ to give the date.

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' );

Ultimately I would like to make this in a cron job, but for now any suggestions to the code would be great.

Category : Wordpress

Tags :