(摘自我对发布的一个类似问题的回答here)
此方法有两个步骤:首先,一个用于保存自定义metabox字段数据的函数(钩住以保存\\u post),其次,一个用于读取新post\\u meta(刚刚保存)、验证它并根据需要修改保存结果的函数(也钩住以保存\\u post,但在第一个之后)。如果验证失败,validator函数实际上会将post\\u状态改回“挂起”,从而有效阻止发布帖子。
由于save\\u post函数被多次调用,因此每个函数都有检查,仅在用户想要发布时执行,并且仅针对您的自定义post类型(mycustomtype)。
我通常还会添加一些自定义的通知消息,以帮助用户了解他们的帖子没有发布的原因,但这些消息在这里包含起来有点复杂。。。
add_action(\'save_post\', \'save_my_fields\', 10, 2);
add_action(\'save_post\', \'completion_validator\', 20, 2);
function save_my_fields($pid, $post) {
// don\'t do on autosave or when new posts are first created
if ( ( defined( \'DOING_AUTOSAVE\' ) && DOING_AUTOSAVE ) || $post->post_status == \'auto-draft\' ) return $pid;
// abort if not my custom type
if ( $post->post_type != \'mycustomtype\' ) return $pid;
// save post_meta with contents of custom field
update_post_meta($pid, \'mymetafield\', $_POST[\'mymetafield\']);
}
function completion_validator($pid, $post) {
// don\'t do on autosave or when new posts are first created
if ( ( defined( \'DOING_AUTOSAVE\' ) && DOING_AUTOSAVE ) || $post->post_status == \'auto-draft\' ) return $pid;
// abort if not my custom type
if ( $post->post_type != \'mycustomtype\' ) return $pid;
// init completion marker (add more as needed)
$meta_missing = false;
// retrieve meta to be validated
$mymeta = get_post_meta( $pid, \'mymetafield\', true );
// just checking it\'s not empty - you could do other tests...
if ( empty( $mymeta ) ) {
$meta_missing = true;
}
// on attempting to publish - check for completion and intervene if necessary
if ( ( isset( $_POST[\'publish\'] ) || isset( $_POST[\'save\'] ) ) && $_POST[\'post_status\'] == \'publish\' ) {
// don\'t allow publishing while any of these are incomplete
if ( $meta_missing ) {
global $wpdb;
$wpdb->update( $wpdb->posts, array( \'post_status\' => \'pending\' ), array( \'ID\' => $pid ) );
// filter the query URL to change the published message
add_filter( \'redirect_post_location\', create_function( \'$location\',\'return add_query_arg("message", "4", $location);\' ) );
}
}
}
对于多个metabox字段,只需添加更多完成标记,检索更多post\\u meta并进行更多测试。。