0

我在 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"]);
    }
4

1 回答 1

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'] )行中,将“post”更改为您的帖子类型

于 2012-11-03T08:42:47.600 回答