我正在尝试修改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,数据已经在某处转义(括号),但我需要原始数据。
请考虑所有要求,提出修改数据的正确方法。
最合适的回答,由SO网友:Nguyễn Văn Được 整理而成
首先,对数据进行了清理here (第2997行)。
如果您不想在操作上运行任何插件/主题save_post
. 用户功能remove_all_actions
删除与操作挂钩的所有函数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
];
// Backup actions
global $wp_filter, $merged_filters;
$backup_wp_filter = $wp_filter;
$backup_merged_filters = $merged_filters;
// Remove all functions which hooked to this action, to prevent run twice.
remove_all_actions(\'save_post\');
// Update the post into the database
wp_update_post($update_data);
// restore actions
$wp_filter = $backup_wp_filter;
$merged_filters = $backup_merged_filters;
}