使用挂钩save_post
并在“正常”保存元字段例程之后执行保存的函数中放置一个if。
add_action( \'save_post\', \'this_is_the_function_name\' );
function this_is_the_function_name( $post_id ) {
// No auto saves
if( defined( \'DOING_AUTOSAVE\' ) && DOING_AUTOSAVE ) return;
// make sure the current user can edit the post
if( ! current_user_can( \'edit_post\' ) ) return;
// assure the post type
if ( ! get_post_type($post_id) == \'cards\' ) return;
// assure the data are sended by the form
if (
! isset($_POST[\'my_cards_activity\']) ||
! isset($_POST[\'my_cards_datetime\']) || ! isset(\'my_cards_user\')
) return;
$activity = $_POST[\'my_cards_activity\'];
// and now the simply logic
if ( $activity == 1 ) {
$datetime = $_POST[\'my_cards_datetime\'];
$user = $_POST[\'my_cards_user\'];
} else {
$datetime = \'\';
$user = \'\';
}
// save data as array
$meta_data = compact("activity", "datetime", "user");
update_post_meta($post_id, \'card_data\', $meta_data);
// if you want can save data as 3 different meta fields in this case
// delete the previous 2 lines and uncommente the following
// update_post_meta($post_id, \'card_activity\', $activity);
// update_post_meta($post_id, \'datetime\', $datetime);
// update_post_meta($post_id, \'user\', $user);
}
如果在元数据库中设置了nonce字段,请在保存之前对其进行检查。
看见Codex 适用于: