我正在尝试修改post save操作的post数据。
首先我试着用save_post
像那样钩住
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);
}
这里的问题是wp_update_post($update_data);
触发器save_post
对其他插件再次执行操作,因此除我的插件外,所有插件都被执行了两次,这很糟糕。然后我找到了另一个钩子wp_insert_post_data
并添加我的处理逻辑
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;
}
它的工作钩子没有被调用两次,但问题的时间wp_insert_post_data
是triggerd,数据已经在某处转义(括号),但我需要原始数据。请考虑所有要求,提出修改数据的正确方法。