Wordpress元盒如何找到保存功能


How a Wordpress metabox manages to find the save function

我正在制作一个wordpress元盒子,我想知道元盒子的html部分是如何找到保存功能的。这是我正在使用的整个代码,它适用于

<?php
function true_add_a_metabox() {
    add_meta_box(
        'true_metabox', // metabox ID, it also will be it id HTML attribute
        'The Detailed Custom Meta Box', // title
        'true_display_metabox', // this is a callback functions, which will be print HTML of our metabox
        'post', // post type
        'normal', // position of the screen where metabox shoul be displayed (normal, side, advanced)
        'default' // priority over another metaboxes on this page (default, low, high, core)
    );
}
add_action( 'admin_menu', 'true_add_a_metabox' );
function true_display_metabox($post) {
    /*
     * needs for security checks
     */
    wp_nonce_field( basename( __FILE__ ), 'true_metabox_nonce' );
    /*
     * lets add a simple textarea field
     */
    $html .= '<p><label>SEO title <input type="text" name="seotitle" value="' . get_post_meta($post->ID, 'true_title',true) . '" /></label></p>';
    /*
     * add a checkbox
     */
    $html .= '<p><label><input type="checkbox" name="noindex"';
    $html .= (get_post_meta($post->ID, 'true_noindex',true) == 'on') ? ' checked="checked"' : '';
    $html .= ' /> Turn of page visibility for search engines</label></p>';
    /*
     * print all of this
     */
    echo $html;
}
function true_save_post_meta( $post_id, $post ) {
    /* 
     * Security checks
     */
    if ( !isset( $_POST['true_metabox_nonce'] ) || !wp_verify_nonce( $_POST['true_metabox_nonce'], basename( __FILE__ ) ) )
        return $post_id;
    /* 
     * Check current user permissions
     */
    $post_type = get_post_type_object( $post->post_type );
    if ( !current_user_can( $post_type->can->edit_post, $post_id ) )
        return $post_id;
    /*
     * Check if the autosave
     */
    if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) 
        return $post_id;
    if ($post->post_type == 'post') { // define your own post type here
        update_post_meta($post_id, 'true_title', esc_attr($_POST['seotitle']));
        update_post_meta($post_id, 'true_noindex', $_POST['noindex']);
    }
    return $post_id;
}
add_action( 'save_post', 'true_save_post_meta', 10, 2 );
?>

在生成html true_display_metabox的函数中,没有提到保存选项的true_save_post_meta。有人能解释一下这个代谢盒是如何保存数据的吗?。

您正在对save_post操作调用true_save_post_meta(在代码的最后一行)。这意味着每次保存帖子时,true_save_post_meta函数都会运行。元框中的数据将包含在$_POST对象中,然后true_save_post_meta使用该对象将这些值保存在数据库中。