我有一个带有几个自定义字段的自定义帖子类型。我希望对这些字段进行一些验证,因为它们将被其他服务在下游使用。因此,重要的是,只有正确输入后才能保存。验证相当复杂,需要自定义逻辑。
不幸的是,在这种特殊情况下使用插件也不起作用。
在这种情况下是否有理想的挂钩?从更高的层面来看,最好的方法是什么。
我有一个带有几个自定义字段的自定义帖子类型。我希望对这些字段进行一些验证,因为它们将被其他服务在下游使用。因此,重要的是,只有正确输入后才能保存。验证相当复杂,需要自定义逻辑。
不幸的是,在这种特殊情况下使用插件也不起作用。
在这种情况下是否有理想的挂钩?从更高的层面来看,最好的方法是什么。
中的示例代码add_meta_box()
文档使用save_post
钩子(在wp_insert_post()
函数)从metabox添加自定义字段数据。
您必须在元数据库中使用类似的内容,这不是验证数据的合适位置吗?。。
(摘自我对发布的一个类似问题的回答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并进行更多测试。。我在WordPress中有以下查询来调用自定义post meta,一切正常,只有一个例外,无论哪个查询是第二个查询,都没有响应任何内容。很抱歉WordPress的帖子,但对于那些不熟悉\'get_post_meta($post->ID\' 正在检索第一个帖子的帖子ID,然后在第二个帖子中回显相同的帖子ID,我需要关闭第一个查询,但不知道如何关闭。 <h3 class=\"body_heading\"> <?php $soon_e