除了其他答案之外,这里还有一个小插件,可以确保代码只执行一次。如果数据被稍后运行的插件重置,请尝试使用PHP_INT_MAX -1
作为优先级(不适用于公共分发的插件)。在这种情况下,必须为remove_filter()
, 否则将不会删除回调。
<?php
/**
* Plugin Name: (WPSE) Static post date
* Description: Keep the post date as the original date for posts published as private
*/
namespace WPSE;
add_filter( \'wp_insert_post_data\', \'\\WPSE\\save\', 10, 2 );
function save( $post, $raw ) {
if ( ! in_array( $post[\'post_status\'], [ \'private\', \'pending\', ] ) ) {
return $post;
}
if ( \'your_post_type\' !== $post[\'post_type\'] ) {
return $post;
}
$date = get_post_field( \'post_date\', $post[\'ID\'], \'raw\' );
$post[\'post_date\'] = $date;
$post[\'post_date_gmt\'] = get_gmt_from_date( $date );
return $post;
}
add_action( \'transition_post_status\', function() {
# Make sure above callback is only triggered once
remove_filter( \'wp_insert_post_data\', \'\\WPSE\\save\' );
} );
IIRC以上代码的主要问题是
private_to_published
筛选器已弃用,因此没有足够具体的内容
aside from a post type status filter. 试试下面的插件,看看它是否有效(如果你的帖子类型真的被命名了
mycpt
):
<?php
/* Plugin Name: (WPSE) Test post type status actions */
add_action( \'private_mycpt\', function( $ID, \\WP_Post $post ) {
var_dump( current_filter() );
exit;
}, 10, 2 );