首页 > 解决方案 > 在 Woocommerce 订单上使用 save_post 挂钩时出现“未定义索引:post_type”

问题描述

我的 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' ] ) );
}

谁能发现错误?

标签: phpwordpresswoocommerceordershook-wordpress

解决方案


钩子中$_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 文件中。它应该更好地工作。


推荐阅读