Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I developed a custom plugin which rewrite some content of my posts, but when i move a post to trash, the action hook 'save_post' is triggered and the post is not deleted.

A simplified version of my code :

add_action('save_post', 'rewrite_post', 10, 2);

function rewrite_post($post_id) {
    remove_action('save_post', 'rewrite_post');

    $title = preg_replace('/\_/', ' ', get_the_title($post_id));
    $my_post = array();
    $my_post['ID'] = $post_id;
    $my_post['post_title'] = $title;
    $my_post['post_status'] = 'publish';
    wp_update_post($my_post);

    add_action('save_post', 'rewrite_post');
}

How can i prevent this hook getting triggered when i delete posts ?

share|improve this question
add comment

1 Answer 1

up vote 1 down vote accepted

It's probably easiest to just check the post status within your function.

Untested:

add_action( 'save_post', 'rewrite_post', 10, 2 );

function rewrite_post( $post_id ) {
    if ( 'trash' != get_post_status( $post_id ) ) {
        remove_action( 'save_post', 'rewrite_post' );
        $title = preg_replace( '/\_/', ' ', get_the_title( $post_id ) );
        $my_post = array( );
        $my_post['ID'] = $post_id;
        $my_post['post_title'] = $title;
        $my_post['post_status'] = 'publish';
        wp_update_post( $my_post );
        add_action( 'save_post', 'rewrite_post' );
    }
}
share|improve this answer
    
It works, thank you ! But when i edit my post the hook is triggered, it is possible to not trigger the hook when deleting and updating posts ? –  sawa73 Apr 5 '13 at 20:14
    
Check this answer. –  vancoder Apr 5 '13 at 21:03
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.