How to filter content post only on save

I wonder how can I trigger filter hook only when post is saved with new revision directly after user clicked save button or publish new post.

My idea is to replace specific parts of the post, but I don’t need to trigger my filter each time ajax request for autosaving is sent or new post draft is created.

I am using this filter right now (don’t pay attention to var_dump)

        add_filter('wp_insert_post_data', array(&$this, 'filter_post_data'), '99', 2);
  function filter_post_data($data, $postarr)
    {
        var_dump($data);
        var_dump($postarr);
        exit;
        // Change post title
        return $data;
    }

And this filter is triggered each time post data is going to be saved into database. But I need to trigger this filter only when user clicks save button.

How can I achieve this ? Should I just check post type, status … in postarr to determine if this post is going to be saved. How can I be sure that the post is save on user click ? (what argument can tell me this)

Thanks.

2 Answers
2

Look at 'save_post' and
Post Status Transitions.

save_post is an action triggered whenever a post or page is created or updated, which could be from an import, post/page edit form, xmlrpc, or post by email. The data for the post is stored in $_POST, $_GET or the global $post_data, depending on how the post was edited. For example, quick edits use $_POST. Since this action is triggered right after the post has been saved, you can easily access this post object by using get_post($post_id)

The revision functions can tell you whether this is an autosave:
wp_is_post_revision() / wp_get_post_revisions().

function wpse_save_post( $post_id ) {

    // If this is just a revision, so we can ignore it.
    if ( wp_is_post_revision( $post_id ) )
        return;

    $post_title = get_the_title( $post_id );
    $post_url = get_permalink( $post_id );
    $subject="A post has been updated";

    $message = "A post has been updated on your website:\n\n";
    $message .= $post_title . ": " . $post_url;
}

add_action( 'save_post', 'wpse_save_post' );

Here you can update the post content after it was saved using wp_update_post(). But be sure to avoid the infinite loop.

function my_function( $post_id ){
    if ( ! wp_is_post_revision( $post_id ) ){

        // unhook this function so it doesn't loop infinitely
        remove_action('save_post', 'my_function');

        // update the post, which calls save_post again
        wp_update_post( $my_args );

        // re-hook this function
        add_action('save_post', 'my_function');
    }
}
add_action('save_post', 'my_function');

Leave a Comment