正如Peattie先生和Nowell先生所指出的,您应该将检查帖子类型作为save_post
作用
这里有几种方法,
add_action( \'save_post\', \'prefix_my_save_post_action\', 10, 3 );
function prefix_my_save_post_action( $post_id, $post, $update ) {
// Check for single post type
if ( \'my_post_type\' !== $post->post_type ) {
return;
}
// Check multiple post types with in_array()
$valid_post_types = array(
\'post\' => true,
\'page\' => true,
\'post_type_a\' => true,
\'post_type_b\' => true
);
if ( ! in_array( $post->post_type, $valid_post_types ) ) {
return;
}
// or with isset() <-- uses array keys
if ( ! isset( $valid_post_types[$post->post_type] ) ) {
return;
}
// Do stuff
}
还有
save_post_{$post->post_type}
可用于直接针对特定post类型保存操作的操作。
add_action( \'save_post_my_post_type\', \'prefix_my_save__cpt_post_action\', 10, 3 );
function prefix_my_save_post_action( $post_id, $post, $update ) {
// No need to check for post type as it is already in the action
// Do stuff
}