using wp_update_post on save_post

im trying to update a posts date (-1 year), when you hit update. but it causes an infinite loop.

any other ways of doing this?

thanks.

function change_year($post_id, $post){
if ( $post->post_type == 'post' ) {
    $format = 'Y-m-d H:i:s'; 
    $id = $post->ID;
    $old_date = $post->post_date;
    $old_gmt_date = $post->post_date_gmt;
    $new_date = date( $format, strtotime( '-1 year' , strtotime( $old_date ) ) );
    $new_date_gmt = date( $format, strtotime( '-1 year' , strtotime( $old_gmt_date ) ) );

    $new_values = array (
        'ID' => $id,
        'post_date' => $new_date,
        'post_date_gmt' => $new_date_gmt
    );

    wp_update_post( $new_values );
}
}

add_filter('save_post', 'change_year',10,2);

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The reason it’s going to be infinite is that every time you save the post, it’s calling change_year…which then calls wp_update_post … which fires the save_post filter.

After some review and research, I’m thinking that you should probably avoid the save_post filter.

Try using this filter:
http://codex.wordpress.org/Plugin_API/Filter_Reference/wp_insert_post_data

It gives you really what you want.

Here’s an example of it editing posted data:

function filter_handler( $data , $postarr ) {
    $data[ 'post_title' ] = $postarr[ 'post_title' ] . 'RAWR!';
    return $data;
}
add_filter( 'wp_insert_post_data' , 'filter_handler' , '99', 2 );

That will take any post that I save and add ‘RAWR!’ to the end of the string.

Hope this helps.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x