How to automatic update date and time when save custom post type

admin2025-06-05  0

I need to update date and time when I save posts. I see the code on the following thread, but I need to have this trick only for posts contained in my custom post 'new_cpt'

Is it possible?

ref: Update post date to modified date automatically

I need to update date and time when I save posts. I see the code on the following thread, but I need to have this trick only for posts contained in my custom post 'new_cpt'

Is it possible?

ref: Update post date to modified date automatically

Share Improve this question edited Dec 5, 2018 at 13:49 fuxia 107k39 gold badges255 silver badges461 bronze badges asked Dec 5, 2018 at 13:22 GiulioGiulio 511 silver badge8 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 2

Using your example link, I just added an IF to check for post_type.

function reset_post_date_wpse_121565($data,$postarr) {
    // var_dump($data,$postarr);  die;// debug
    if($data['post_type'] == 'new_cpt'){
        $data['post_date'] = $data['post_modified'];
        $data['post_date_gmt'] = $data['post_modified_gmt'];
        return $data;
    }    
}
add_filter('wp_insert_post_data','reset_post_date_wpse_121565',99,2);

Yes, it is possible. All you have to do is to check the post type before you update dates:

function reset_post_date_wpse_321084( $data, $postarr ) {
    if ( array_key_exists('ID', $postarr) ) {
        $post_id = $postarr['ID'];

        if ( 'new_cpt' == get_post_type( $post_id ) ) {
            $data['post_date'] = $data['post_modified'];
            $data['post_date_gmt'] = $data['post_modified_gmt'];
        }
    }

    return $data;
}
add_filter( 'wp_insert_post_data','reset_post_date_wpse_321084', 99, 2 );
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749126919a316593.html

最新回复(0)