Wordpress - 元字段更新

时间:2012-11-02 19:02:21

标签: wordpress custom-post-type

我在Wordpress中为自定义帖子类型创建了几个元字段。它们是“价格”和“细节”。如果我进入“编辑帖子”页面,并且我在其中一个字段中更改某些内容,但随后决定通过在浏览器中点击“返回”或关闭窗口来离开页面,我会从浏览器收到警告“你确定要离开这个页面吗?“当我点击“是”时,它会删除这两个字段中的所有内容,甚至是在编辑之前存储的内容。

知道为什么会这样吗?

这是我在functions.php中的一些代码:

add_action("admin_init", "admin_init");
function admin_init()
    {
        add_meta_box("price", "Price", "price_field", "product", "normal", "high");
        add_meta_box("details", "Details", "details_field", "product", "normal", "high");
    }

    function price_field()
    {
        global $post;
        $custom = get_post_custom($post->ID);
        $price = $custom["price"][0];
        ?>
        <label>Price: $</label>
        <input name="price" value="<?php echo $price; ?>" />
        <?php
    }

    function details_field()
    {
        global $post;
        $custom = get_post_custom($post->ID);
        $details = $custom["details"][0];
        ?>
        <label>Details:</label>
        <input name="details" rows='5' value="<?php echo $details; ?>" />
        <?php
    }


    /*--------------------------------*/
    /* Save PRICE and DETAILS fields */
    /*--------------------------------*/
    add_action('save_post', 'save_details');
    function save_details()
    {
        global $post;
        update_post_meta($post->ID, "price", $_POST["price"]);
        update_post_meta($post->ID, "details", $_POST["details"]);
    }

1 个答案:

答案 0 :(得分:0)

这是因为您没有在保存详细信息方法中添加过滤。记住,即使你没有点击更新或发布按钮,一旦帖子在草稿中自动保存,也会调用动作钩子“save_post”。试试这个

add_action('save_post', 'save_details');

 function save_details($post_id){
      if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
            return;

        // uncomment if youre using nonce
        //if ( !wp_verify_nonce( $_POST['my_noncename'], plugin_basename( __FILE__ ) ) )
          //       return;


        // Check permissions
        //change the "post" with your custom post type
        if ( 'post' == $_POST['post_type'] )
        {
           if ( !current_user_can( 'edit_page', $post_id ) )
                return;
        }
        else
        {
           if ( !current_user_can( 'edit_post', $post_id ) )
                return;
        }

      //if success go to your process
      //you can erase your global $post and dont use $post->ID rather change it with $post_id since its our parameter
      update_post_meta($post_id, "price", $_POST["price"]);
      update_post_meta($post_id, "details", $_POST["details"]);
 }

注意: if('post'== $ _POST ['post_type'])行中,将“发布”更改为您的帖子类型