自定义帖子类型元框未保存

时间:2018-11-07 12:07:54

标签: php wordpress custom-post-type

我在WordPress中创建了一个名为“百科全书”的CPT。然后,我在其中创建了几个元字段,只是一些简单的文本字段,但是目前它们还没有保存,我不知道为什么。有人可以帮忙吗?

/*
=========================================================================
Custom Meta Fields - English version
=========================================================================
*/

function custom_meta_box_markup()
{
    wp_nonce_field(basename(__FILE__), "meta-box-nonce");

    ?>
        <div>
            <label for="english_version">Description</label>
            <input name="english_version" type="text" value="<?php echo get_post_meta($object->ID, "english_version", true); ?>">
        </div>


<?php }

function add_custom_meta_box()
{
    add_meta_box("english_version", "English Version", "custom_meta_box_markup", "encyclopedia", "advanced", "high", null);
    //add_meta_box("german-version", "German Version", "custom_meta_box_markup", "encyclopedia", "advanced", "high", null);
}

add_action("add_meta_boxes", "add_custom_meta_box");

function save_custom_meta_box($post_id, $post, $update)
{
    if (!isset($_POST["meta-box-nonce"]) || !wp_verify_nonce($_POST["meta-box-nonce"], basename(__FILE__))){
        return $post_id;
    }

    if(!current_user_can("edit_post", $post_id)){
        return $post_id;
    }

    if(defined("DOING_AUTOSAVE") && DOING_AUTOSAVE){
        return $post_id;
    }

    $slug = "post";
    if($slug != $post->post_type){
        return $post_id;
    }

    $meta_box_text_value = "";

    if(isset($_POST["english_version"]))
    {
        $meta_box_text_value = $_POST["english_version"];
    }   
    update_post_meta($post_id, "english_version", $meta_box_text_value);

}

add_action("save_post_encyclopedia", "save_custom_meta_box", 10, 3);

相关代码在上面,我目前将其存储在子主题的functions.php文件中。

谢谢

1 个答案:

答案 0 :(得分:1)

根据我对您的问题的评论,修正了问题后,代码仍然有问题。

在元框输出函数custom_meta_box_markup上,您使用的是get_post_meta($object->ID, "english_version", true),而没有定义$object

我已经测试了您的代码,并且您的数据已保存在DB中。但是由于$object->ID不返回任何内容,因此在输入文本字段上未显示任何内容。 custom_meta_box_markup收到一个$post对象,您错过了它。像这样更新您的代码:

function custom_meta_box_markup($post) {
    wp_nonce_field(basename(__FILE__), "meta-box-nonce");

    ?>
    <div>
        <label for="english_version">Description</label>
        <input name="english_version" type="text" value="<?php echo get_post_meta($post->ID, "english_version", true); ?>">
    </div>


<?php }
相关问题