I have a plugin and I would like to be able to run the post content through some filters before it is saved to the database. From looking at the plugin api, I see that two hooks that look like they might be helpful:
save_post wp_insert_post
The only problem is that it looks like save_post does not need return a variable, and so I don’t know how to filter the content, and wp_insert_post looks documented.
I’d like to do something like this:
add_action('whatever_hook_name','my_function');
function my_function($post_content){
return $post_content.' <br> This post was saved on '.time();
}
I am going to do something more useful than append a timestamp, namely running some regex filters, but this is the general type of filter / action I’m trying to add.
Update
Please note that I want to intercept the data on it’s way to being saved in the database – not when it is being displayed in the post (eg: Not by adding a filter to the_content)
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 wp_insert_post_data filter can do that:
add_filter( 'wp_insert_post_data' , 'filter_post_data' , '99', 2 );
function filter_post_data( $data , $postarr ) {
// Change post title
$data['post_title'] .= '_suffix';
return $data;
}
Method 2
Use filter content_save_pre exactly like the_content — the difference is that it operates when a post is saved, rather than displayed.
http://codex.wordpress.org/Plugin_API/Filter_Reference/content_save_pre
Method 3
You can also check for the hook pre_post_update
add_action('pre_post_update', 'before_data_is_saved_function');
function before_data_is_saved_function($post_id) {
}
Method 4
Add the following code to the active theme to replace <shell> with [shell] before saving:
add_filter('content_save_pre', 'my_sanitize_content', 10, 1);
function my_sanitize_content($value) {
return str_replace('<shell>', '[shell]', $value);
}
Method 5
If you just want to add something similar at the end of all the posts, then I would suggest you use the the_content filter.
function append_to_content( $content ) {
global $post;
return $content.'<br />This post was saved on '.$post->post_date;
}
add_filter( 'the_content', 'append_to_content' );
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