在Woocommerce订单上使用save_post钩子时出现“未定义索引:post_type”

时间:2018-11-12 12:57:44

标签: php wordpress woocommerce orders hook-wordpress

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

谁能发现错误?

2 个答案:

答案 0 :(得分:1)

问题在以下代码行中:

Dante, 4 Dante, 4 Dante, 4 Dante, 4 Dante, 4 5, 0

它适用于所有其他帖子类型,但是如果根本没有设置CocoaPods: not installed /Library/Ruby/Gems/2.3.0/gems/claide-1.0.2/lib/claide/command.rb:439:in `help!': [!] You cannot run CocoaPods as root. (CLAide::Help) 并在警告之上触发,则也会触发它。

要对其进行修复,请添加检查其是否实际设置:

export GEM_HOME=$HOME/.gem
export PATH=$GEM_HOME/bin:/Users/stephensmith/.gem/ruby/2.3.0/bin:$PATH

希望可以解决该警告

答案 1 :(得分: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文件中。它应该更好地工作。