Вывести данные json в корзину woocommerce и сохранить их в заказе - PullRequest
0 голосов
/ 08 октября 2019

Я отправляю некоторые пользовательские данные через AJAX, и мне нужно отобразить их в корзине woocommerce и сохранить в заказе, чтобы они отображались в бэк-офисе и в заказе клиента. Данные представляют собой json, который содержит несколько массивов, например:

var boletos = { 
  "boleto1": ["1", "2", "3"],
  "boleto2": ["10", "20", "30"]         
}

Дело в том, что информация поступает, но я не могу отобразить ее должным образом, так как сейчас она выглядит такв корзине: {\ "boleto1 \": [\ "1 \", \ "2 \", \ "3 \"], \ "boleto2 \": [\ "10 \", \ "20 \",\ "30 \"]}

Это мой AJAX-вызов ('dia' - это другое пользовательское значение, которое мне нужно отобразить и сохранить, но это всего лишь одно значение):

jQuery.post("example.com", {  
    dia: dia,
    boletos: JSON.stringify(boletos)

 }, function(resultado, status){

    window.location = "example.com";

});

Это то, что у меня есть в моем файле functions.php:

/**
 * Save numbers in the cart.
 **/
function add_boletos( $cart_item_data, $product_id, $variation_id ) {

    $dia_boletos = filter_input( INPUT_POST, 'dia' );

    $numeros_boletos = $_POST['boletos'];

    //I tried with implode, decode and a loop...
    $prueba = implode(",", $numeros_boletos);
    $json = json_decode($numeros_boletos, true);
   $return = $numeros_boletos; 
    foreach($return as $valor){
        echo '<script language="javascript">console.log('.$valor.');</script>';
    }


    if ( empty( $numeros_boletos ) || empty( $dia_boletos )) {
        return $cart_item_data;
    }

    $cart_item_data['dia'] = $dia_boletos;
    $cart_item_data['boletos'] = $numeros_boletos; /*...but if I change here $numeros_boletos
    for $json, $prueba or $valor, it writes nothing in the cart,though in the console they
    return an object.*/

    return $cart_item_data;
}

add_filter( 'woocommerce_add_cart_item_data', 'add_boletos', 10, 3 );

/**
 * Display numbers in the cart.
 **/
function muestra_boletos( $item_data, $cart_item ) {
    if ( empty( $cart_item['dia'] ) || empty( $cart_item['boletos'] ) ) {
        return $item_data;
    }   

        $item_data[] = array(
          'key'     => __( 'Día', 'iconic' ),
          'value'   => wc_clean( $cart_item['dia'] ),
          'display' => '',
        );

    $item_data[] = array(
           'key'     => __( 'Combinaciones', 'iconic' ),
           'value'   => wc_clean( $cart_item['boletos']),
           'display' => '',
         );

}

add_filter( 'woocommerce_get_item_data', 'muestra_boletos', 10, 2 );


/**
 * Save data in the order.
 **/
add_action( 'woocommerce_get_cart_item_from_session',  'cart_item_from_session' , 99, 2 );

function cart_item_from_session( $data, $values ) {
    $data[ 'dia' ] = isset( $values[ 'dia' ] ) ? $values[ 'dia' ] : '';
    $data[ 'boletos' ] = isset( $values[ 'boletos' ] ) ? $values[ 'boletos' ] : '';
    return $data;
}

add_filter( 'woocommerce_add_order_item_meta', 'add_item_meta_order', 10, 3 );

function add_item_meta_order( $item_id, $values ) {
    if ( !is_null( $values[ 'dia' ] ) ) {
        wc_add_order_item_meta( $item_id, 'dia', $values[ 'dia' ] );
    }
    if ( !is_null( $values[ 'boletos' ] ) ) {
        wc_add_order_item_meta( $item_id, 'boletos', $values[ 'boletos' ] );
    }
}

Для извлечения данных я попытался в первой функции: $cart_item_data['boletos'] = $numeros_boletos->boleto1, $cart_item_data['boletos'] = $numeros_boletos['boleto1'], $cart_item_data['boletos'] = $numeros_boletos[0] (также япопытался изменить $numeros_boletos для $json, $prueba и $valor).

Во второй функции, которую я попытался:

$item_data[] = array(
   'key'     => __( 'Combinaciones', 'iconic' ),
   'value'   => wc_clean( $cart_item['boletos']->boleto1),
   'display' => '',
);


$item_data[] = array(
   'key'     => __( 'Combinaciones', 'iconic' ),
   'value'   => wc_clean( $cart_item['boletos']['boleto1']),
   'display' => '',
);

$item_data[] = array(
   'key'     => __( 'Combinaciones', 'iconic' ),
   'value'   => wc_clean( $cart_item['boletos'][0]),
   'display' => '',
);

После всех этих попыток ничего не отображается вКорзина. Я знаю, что это должно быть что-то очень глупое, но я не эксперт по WordPress и не очень хорош в работе с JSON и массивами. Как я могу правильно показать цифры? Заранее большое спасибо.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...