我开发了一个自定义插件,可以重写我帖子的一些内容,但当我将帖子移动到垃圾箱时,会触发动作挂钩“save\\u post”,并且不会删除帖子。
我的代码的简化版本:
add_action(\'save_post\', \'rewrite_post\', 10, 2);
function rewrite_post($post_id) {
remove_action(\'save_post\', \'rewrite_post\');
$title = preg_replace(\'/\\_/\', \' \', get_the_title($post_id));
$my_post = array();
$my_post[\'ID\'] = $post_id;
$my_post[\'post_title\'] = $title;
$my_post[\'post_status\'] = \'publish\';
wp_update_post($my_post);
add_action(\'save_post\', \'rewrite_post\');
}
如何防止在删除帖子时触发此挂钩?
最合适的回答,由SO网友:vancoder 整理而成
在您的函数中检查post状态可能是最简单的方法。
未经测试:
add_action( \'save_post\', \'rewrite_post\', 10, 2 );
function rewrite_post( $post_id ) {
if ( \'trash\' != get_post_status( $post_id ) ) {
remove_action( \'save_post\', \'rewrite_post\' );
$title = preg_replace( \'/\\_/\', \' \', get_the_title( $post_id ) );
$my_post = array( );
$my_post[\'ID\'] = $post_id;
$my_post[\'post_title\'] = $title;
$my_post[\'post_status\'] = \'publish\';
wp_update_post( $my_post );
add_action( \'save_post\', \'rewrite_post\' );
}
}