Change post status by custom fields

admin2025-06-05  2

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

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

Share Improve this question asked Nov 30, 2018 at 18:56 GiulioGiulio 511 silver badge8 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 2

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

    // 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.
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749137823a316681.html

最新回复(0)