I am trying to modify post data on post save action.
Firstly I tried to use save_post
hook like that
function post_save_action($post_id, $post, $update)
{
if ($this->is_temp_saving_post($post, $post_id)) {
return;
}
// Check user permissions
if (!current_user_can('edit_post', $post_id))
return;
// Update post
if (!$this->is_proper_post_type($post)) {
return;
}
$processed_content = $this->process_post_data($post);
$update_data = [
self::POST_ID => $post_id,
self::POST_CONTENT => $processed_content
];
// Prevent infinite loop
remove_action('save_post', array($this, 'post_save_action'), 99);
// Update the post into the database
wp_update_post($update_data);
// Add hook again
add_action('save_post', array($this, 'post_save_action'), 99);
}
The problem here is that wp_update_post($update_data);
triggers save_post
action again for other plugins, so all plugins except mine are being executed twice, and that is bad.
Then I found another hook wp_insert_post_data
and add my processing logic
public function post_insert_filter($data, $postattr)
{
$post_id = $postattr['ID'];
$post_object = $this->convertToObject($data);
$post_object->ID = $post_id;
if ($this->is_temp_saving_post($post_object, $post_id)) {
return $data;
}
if (!current_user_can('edit_post', $post_id)) {
return $data;
}
// Update post
if (!$this->is_proper_post_type($post_object)) {
return $data;
}
$processed_content = $this->process_post_data($post_object);
$data[self::POST_CONTENT] = $processed_content;
return $data;
}
It works hook is not called twice, but the problem for the time wp_insert_post_data
is triggerd, data already has been escaped(parentheses) somewhere, but I need raw data here.
Please suggest the right way to modify data considering all requirements.