I'd like to update my post status (of my own CPT) based on custom field "played". If played is 1 i want that the post shall be published, but if the custom field played is 0 the post shall be draft also if I tried to publish it.

Is it possible?

I tried to search in the forum but nothing found that works... also tried the code here but not working...

How to Update post status using meta data in Custom post TYpe


All you need to do is to use save_post hook. Here's how:

function change_post_status_based_on_custom_field( $post_id ) {
    // If this is just a revision, don't do anything.
    if ( wp_is_post_revision( $post_id ) )

    // Get field value
    $value = get_post_meta( $post_id, 'played', true );

    $status = $value ? 'publish' : 'draft';

    // If status should be different, change it
    if ( get_post_status( $post_id ) != $status ) {
        // unhook this function so it doesn't loop infinitely
        remove_action( 'save_post', 'change_post_status_based_on_custom_field' );

        // update the post, which calls save_post again
        wp_update_post( array(
            'ID' => $post_id,
            'post_status' => $status
        ) );

        // re-hook this function
        add_action( 'save_post', 'change_post_status_based_on_custom_field' );
add_action( 'save_post', 'change_post_status_based_on_custom_field' );

That might be quite a bit of code to paste in here, but your strategy should be along the lines of:

  • Hook onto post_save event:
    • make a static variable that you've already checked this, to prevent infinite recursion in the case that you update the post from within this function.
    • check if custom field == 'played'
      • if it is, modify the post status as needed, and do wp_update_post.

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.