1

我的 debug.log 中出现错误,某些代码在结帐时保存了我的自定义字段。我似乎无法找到问题所在:

PHP Notice:  Undefined index: post_type in /wp-content/themes/theme-child/functions.php on line 857

这是我的代码:

// Saving
add_action( 'save_post', 'tcg_save_meta_box_data' );
function tcg_save_meta_box_data( $post_id ) {

    // Only for shop order
    if ( 'shop_order' != $_POST[ 'post_type' ] )
        return $post_id;

    // Check if our nonce is set (and our cutom field)
    if ( ! isset( $_POST[ 'tracking_box_nonce' ] ) && isset( $_POST['tracking_box'] ) )
        return $post_id;

    $nonce = $_POST[ 'tracking_box_nonce' ];

    // Verify that the nonce is valid.
    if ( ! wp_verify_nonce( $nonce ) )
        return $post_id;

    // Checking that is not an autosave
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
        return $post_id;

    // Check the user’s permissions (for 'shop_manager' and 'administrator' user roles)
    if ( ! current_user_can( 'edit_shop_order', $post_id ) && ! current_user_can( 'edit_shop_orders', $post_id ) )
        return $post_id;

    // Saving the data
    update_post_meta( $post_id, 'Other notes', sanitize_text_field( $_POST[ 'tracking_box' ] ) );
}

谁能发现错误?

4

2 回答 2

1

钩子中$_POST['post_type']不可用save_post……这个动作钩子有 3 个可用参数$post_id$post$update。所以改为使用:

add_action( 'save_post', 'tcg_save_meta_box_data', 10, 3 );
function tcg_save_meta_box_data( $post_id, $post, $update ) {

    // Only for shop order
    if ( 'shop_order' != $post->post_type )
        return $post_id;

    // ...

更好:或者以这种方式直接使用复合钩子save_post_shop_order

add_action( 'save_post_shop_order', 'tcg_save_meta_box_data', 10, 3 );
function tcg_save_meta_box_data( $post_id, $post, $update ) {
    // Check if our nonce is set (and our custom field)
    if ( ! isset( $_POST[ 'tracking_box_nonce' ] ) && isset( $_POST['tracking_box'] ) )
        return $post_id;

    $nonce = $_POST[ 'tracking_box_nonce' ];

    // Verify that the nonce is valid.
    if ( ! wp_verify_nonce( $nonce ) )
        return $post_id;

    // Checking that is not an autosave
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
        return $post_id;

    // User capability check: Check if the current user can edit an order 
    if ( ! current_user_can( 'edit_shop_order', $post_id ) )
        return $post_id;

    // Saving the data
    update_post_meta( $post_id, 'Other notes', sanitize_text_field( $_POST[ 'tracking_box' ] ) );
}

代码在您的活动子主题(活动主题)的 function.php 文件中。它应该更好地工作。

于 2018-11-12T14:14:39.873 回答
1

问题在于这些代码行:

// Only for shop order
if ( 'shop_order' != $_POST[ 'post_type' ] )
    return $post_id;

$_POST[ 'post_type' ]它适用于所有其他帖子类型,但当根本没有设置并在警告之上触发时,它也会被触发。

要修复它,请添加检查它是否实际设置:

// Only for shop order
    if ( !isset($_POST[ 'post_type' ]) || 'shop_order' != $_POST[ 'post_type' ] )
        return $post_id;

希望能修复警告

于 2018-11-12T14:14:08.113 回答