我正在编写一个插件,它有一个自定义的帖子类型,主要使用自定义字段。我禁用了CPT的几乎所有功能,以便确保字段遵循某些准则。如果提交表单时所有字段都不符合所有规则,则不会更新任何元数据。当这种情况发生时,WP仍然插入几乎没有任何数据的帖子。我想阻止WP插入空帖子。有没有办法做到这一点?
如何防止WP插入空帖
1 个回复
SO网友:David Sword
由于自动保存功能,帖子将始终存在于WordPress中,一旦输入内容,就会将其插入数据库。所以你不能阻止一个条目,但是你可以在用户点击帖子上的“发布”或“保存”后使用wp_insert_post
, 或save_post
. 通过此操作,您可以执行条件检查,并将post\\u状态从publish更改为draft,或更改插件所需的任何内容。
例如:
function _myplugin_save_post_check($post_id) {
// If this is a revision, get real post ID
if ( $parent_id = wp_is_post_revision( $post_id ) )
$post_id = $parent_id;
// Do whatever conditional checks you want here, like checking the custom feilds values
$custom_feilds = get_post_meta( $post_id, \'whatever\', true );
if ( empty( $custom_feilds ) ) {
// unhook this function so it doesn\'t loop infinitely
remove_action( \'save_post\', \'_myplugin_save_post_check\' );
// update the post as unpublished, or whatever
wp_update_post( array( \'ID\' => $post_id, \'post_status\' => \'draft\' ) );
// re-hook this function
add_action( \'save_post\', \'_myplugin_save_post_check\' );
}
}
add_action( \'save_post\', \'_myplugin_save_post_check\' );
如果自定义元字段\'whatever\'
为空。结束