最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

posts - using wp_update_post on save_post

programmeradmin0浏览0评论

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

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);
Share Improve this question asked Nov 9, 2011 at 21:14 chrismccoychrismccoy 3094 silver badges12 bronze badges 1
  • I would like to add some more info - the solution above makes changes to EVERY post, even if it is e.g. publishing the post by the admin in the backend. See my answer here for more details: wordpress.stackexchange/a/113967/37612 – Asped Commented Sep 12, 2013 at 23:12
Add a comment  | 

1 Answer 1

Reset to default 7

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/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.

发布评论

评论列表(0)

  1. 暂无评论