0

I am looking for a way to change the post status of some posts based on custom field value, from published to pending for example. How might this be possible?

My solution:

$post_ids = array( 1235, 1234, 1228, 1221, 1211, 1212, 1208, 1200 );

foreach($post_ids as $post_id) {
    $post = array( 'ID' => $post_id, 'post_status' => 'pending' );
    wp_update_post($post);
}
  • 1
    How/when do you want the action to be triggered? – jetlej Oct 26 '14 at 4:16
  • It's for posts that are already in the database only, so it will be a one-time thing to set to pending posts that have a custom field with a certain value. With new posts going forward I won't have this value. – amespower Oct 26 '14 at 15:55
0

Paste this onto any page and load the page (or make it a function in functions.php and call that function somewhere)

$args = array(
    'nopaging' => true, // Loop through all posts at once
    'meta_key' => 'YOUR_CUSTOM_FIELD_NAME', // Replace with the name of your custom field
    'meta_value' => 'YOUR_CUSTOM_FIELD_VALUE', // The value of that field you're matching for
);

$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {

    while ( $the_query->have_posts() ) {
        $the_query->the_post();

        // Change the status of each post to pending
        $updated = wp_update_post( array('ID' => $the_query->post->ID, 'post_status' => 'pending' ));

        // Check to see if loop is returning posts, and if they were updated
        echo 'Post #' . $the_query->post->ID . ' - ' . $updated;
    }
}
  • Thanks for your response, but no luck with that. I tried it both ways and tried with other loops on index.php removed, so only that remained, reloaded and nothing happened. Any ideas why? – amespower Oct 26 '14 at 20:48
  • Try echoing wp_user_post to see if it returns a post ID or just 0. – jetlej Oct 26 '14 at 20:51
  • I would also include echo $the_query->post->ID; in the loop to make sure you're actually getting some matching posts with that query. Just updated my response with both testing methods. – jetlej Oct 26 '14 at 20:54
  • Also make sure you have PHP debugging turned on so you can see any errors (in wp-config.php) – jetlej Oct 26 '14 at 20:58
  • Any luck on debugging? – jetlej Oct 27 '14 at 21:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.