«Неопределенный индекс: post_type» при использовании ловушки save_post в заказах Woocommerce - PullRequest
0 голосов
/ 12 ноября 2018

Я получаю сообщение об ошибке в моем 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 голосов
/ 12 ноября 2018

$_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 вашей активной дочерней темы (active theme). Это должно лучше работать.

0 голосов
/ 12 ноября 2018

Проблема в следующих строках кода:

// 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;

Надеюсь, что это исправит предупреждение

...