Сохраняйте и отображайте выбранные пользователем данные в WooCommerce - PullRequest
0 голосов
/ 26 мая 2019

Я использую код, который на странице редактирования продукта показывает флажок «Уровень жаркого».Когда менеджер нажимает на этот флажок, на странице отдельного продукта появляется поле выбора, позволяющее клиенту выбрать «Жареный уровень».

При выборе и добавлении продукта в корзину отображается выбранное значениев самой корзине.Это значение также отображается на странице оформления заказа, на странице «Спасибо», в заказе, в уведомлении по электронной почте и на странице редактирования заказа в панели администратора.

Вот код:

// Display Checkbox Field
add_action('woocommerce_product_options_general_product_data', 'roast_custom_field_add');

function roast_custom_field_add() {
    global $post;

    // Checkbox
    woocommerce_wp_checkbox(
            array(
                    'id' => '_roast_checkbox',
                    'label' => __('Roast Level', 'woocommerce'),
                    'description' => __('Enable roast level!', 'woocommerce')
            )
    );
}

// Save Checkbox Field
add_action('woocommerce_process_product_meta', 'roast_custom_field_save');

function roast_custom_field_save($post_id) {
    // Custom Product Checkbox Field
    $roast_checkbox = isset($_POST['_roast_checkbox']) ? 'yes' : 'no';
    update_post_meta($post_id, '_roast_checkbox', esc_attr($roast_checkbox));
}

// Display Select Box
add_action('woocommerce_before_add_to_cart_button', 'add_roast_custom_field', 0);

function add_roast_custom_field() {
    global $product;

    // If is single product page and have the "roast_checkbox" enabled we display the field
    if (is_product() && $product->get_meta('_roast_checkbox') === 'yes') {

            echo '<div>';

            woocommerce_form_field('roast_custom_options', array(
                    'type' => 'select',
                    'class' => array('my-field-class form-row-wide'),
                    'label' => __('Roast Level'),
                    'required' => false,
                    'options' => array(
                            '' => 'Please select',
                            'Blue' => 'Blue',
                            'Rare' => 'Rare',
                            'Medium Rare' => 'Medium Rare',
                            'Medium' => 'Medium',
                            'Medium Well' => 'Medium Well',
                            'Well Done' => 'Well Done'
                    )
            ), '');

            echo '</div>';
    }
}

// Add as custom cart item data
add_filter('woocommerce_add_cart_item_data', 'add_custom_cart_item_data', 10, 3);

function add_custom_cart_item_data($cart_item_data, $product_id, $variation_id) {
    if (isset($_POST['roast_custom_options'])) {
            $cart_item_data['roast_option'] = wc_clean($_POST['roast_custom_options']);
    }
    return $cart_item_data;
}

// Add custom fields values under cart item name in cart
add_filter('woocommerce_cart_item_name', 'roast_custom_field', 10, 3);

function roast_custom_field($item_name, $cart_item, $cart_item_key) {
    if (!is_cart())
            return $item_name;

    if (isset($cart_item['roast_option'])) {
            $item_name. = '<br /><div class="my-custom-class"><strong>'.__("Roast Level", "woocommerce").
            ':</strong> '.$cart_item['roast_option'].
            '</div>';
    }
    return $item_name;
}

// Display roast custom fields values under item name in checkout
add_filter('woocommerce_checkout_cart_item_quantity', 'roast_custom_checkout_cart_item_name', 10, 3);

function roast_custom_checkout_cart_item_name($item_qty, $cart_item, $cart_item_key) {
    if (isset($cart_item['roast_option'])) {
            $item_qty. = '<br /><div class="my-custom-class"><strong>'.__("Roast Level", "woocommerce").
            ':</strong> '.$cart_item['roast_option'].
            '</div>';
    }
    return $item_qty;
}


// Save chosen slelect field value to each order item as custom meta data and display it everywhere
add_action('woocommerce_checkout_create_order_line_item', 'save_order_item_product_fitting_color', 10, 4);

function save_order_item_product_fitting_color($item, $cart_item_key, $values, $order) {
    if (isset($values['_roast_option'])) {
            $key = __('Roast Level', 'woocommerce');
            $value = $values['_roast_option'];
            $item->update_meta_data($key, $value);
    }
}

Этот код хорошо работает в теме Storefront, но по какой-то причине он не работает в теме, которую я купил в Themeforest.Разработчики не могут помочь, они говорят, что мне нужно связаться с человеком, который написал этот код.И поэтому ...

Я также использую код, который работает в Витрине магазина и в купленной теме.Вот оно - Показать пользовательские поля на странице редактирования заказа в WooCommerce , тех.Он прекрасно работает в этих двух темах.

Насколько я понимаю, это связано с синтаксисом "эхо".В форме «Roast Level» этот синтаксис имеет вид, поэтому форма отображается.При отображении выбранных данных в корзине или на странице оформления заказа этот синтаксис не используется.


ОБНОВЛЕНИЕ

Вот код, без которого не работает"echo":

// Add custom fields values under cart item name in cart
add_filter('woocommerce_cart_item_name', 'roast_custom_field', 10, 3);

function roast_custom_field($item_name, $cart_item, $cart_item_key) {
    if (!is_cart())
            return $item_name;

    if (isset($cart_item['roast_option'])) {
            $item_name. = '<br /><div class="my-custom-class"><strong>'.__("Roast Level", "woocommerce").
        ':</strong> '.$cart_item['roast_option'].
        '</div>';
    }
    return $item_name;
}

// Display roast custom fields values under item name in checkout
add_filter('woocommerce_checkout_cart_item_quantity', 'roast_custom_checkout_cart_item_name', 10, 3);

function roast_custom_checkout_cart_item_name($item_qty, $cart_item, $cart_item_key) {
    if (isset($cart_item['roast_option'])) {
            $item_qty. = '<br /><div class="my-custom-class"><strong>'.__("Roast Level", "woocommerce").
        ':</strong> '.$cart_item['roast_option'].
        '</div>';
    }
    return $item_qty;
}


// Save chosen slelect field value to each order item as custom meta data and display it everywhere
add_action('woocommerce_checkout_create_order_line_item', 'save_order_item_product_fitting_color', 10, 4);

function save_order_item_product_fitting_color($item, $cart_item_key, $values, $order) {
    if (isset($values['_roast_option'])) {
            $key = __('Roast Level', 'woocommerce');
            $value = $values['_roast_option'];
            $item->update_meta_data($key, $value);
    }
}

Я прошу изменить свой код так, чтобы он имел синтаксис "echo", чтобы выбранные данные выводились с использованием "echo".Буду рад вашей помощи!

1 Ответ

2 голосов
/ 31 мая 2019

Следующий код должен работать

/*---------------------------------------------------------------
*Display Select Box
---------------------------------------------------------------*/
add_action( 'woocommerce_before_add_to_cart_button', 'add_roast_custom_field', 0 );
function add_roast_custom_field() {
    global $product;

    // If is single product page and have the "roast_checkbox" enabled we display the field
    if ( is_product() && $product->get_meta( '_roast_checkbox' ) === 'yes' ) {

        echo '<div class="roast_select">';

        $select = woocommerce_form_field( 'roast_custom_options', array(
            'type'          => 'select',
            'class'         => array('my-field-class form-row-wide'),
            'label'         => __('Roast Level'),
            'required'      => false,
            'return'       => false,
            'options'   => array(
                ''      => 'Please select',
                'Blue'  => 'Blue',
                'Rare'  => 'Rare',
                'Medium Rare'   => 'Medium Rare',
                'Medium'    => 'Medium',
                'Medium Well'   => 'Medium Well',
                'Well Done' => 'Well Done'
            )
        ), '' );
        echo $select;
        echo '</div>';
    }
}
/*---------------------------------------------------------------
* Add as custom cart item data
---------------------------------------------------------------*/
add_filter( 'woocommerce_add_cart_item_data', 'add_custom_cart_item_data', 10, 21 );
function add_custom_cart_item_data($cart_item_data, $product_id, $variation_id ){

    if( isset( $_POST['roast_custom_options'] ) ) {
        $cart_item_data['roast_option'] = wc_clean( $_POST['roast_custom_options'] );
    }
    return $cart_item_data;
}
/*---------------------------------------------------------------
* Add custom fields values under cart item name in cart
---------------------------------------------------------------*/

add_filter( 'woocommerce_cart_item_name', 'roast_custom_field', 10, 21 );
function roast_custom_field( $item_name, $cart_item, $cart_item_key ) {
    if( ! is_cart() )
        return $item_name;

    if( isset($cart_item['roast_option']) ) {
        $item_name .= '<br /><div class="my-custom-class"><strong>' . __("Roast Level", "woocommerce") . ':</strong> ' . $cart_item['roast_option'] . '</div>';
    }
    return $item_name;
}

/*---------------------------------------------------------------
* Display roast custom fields values under item name in checkout
---------------------------------------------------------------*/

add_filter( 'woocommerce_checkout_cart_item_quantity', 'roast_custom_checkout_cart_item_name', 10, 21 );
function roast_custom_checkout_cart_item_name( $item_qty, $cart_item, $cart_item_key ) {
    if( isset($cart_item['roast_option']) ) {
        $item_qty .= '<br /><div class="my-custom-class"><strong>' . __("Roast Level", "woocommerce") . ':</strong> ' . $cart_item['roast_option'] . 'гр.</div>';
    }
    return $item_qty;
}

/*---------------------------------------------------------------
* Save chosen slelect field value to each order item as custom meta data and display it everywhere
---------------------------------------------------------------*/
add_action('woocommerce_checkout_create_order_line_item', 'save_order_item_product_fitting_color', 10, 21 );
function save_order_item_product_fitting_color( $item, $cart_item_key, $values, $order ) {
    if( isset($values['roast_option']) ) {
        $key = __('Roast Level', 'woocommerce');
        $value = $values['roast_option'];
        $item->update_meta_data( $key, $value ,$item->get_id());
    }
}

/*--------------------------------------------------------------------
The following code played the important role in your theme

Your add to cart form takes the values when user clicks on add to cart button 
After it ajax runs and takes the values from the butoons custom attribute
like data-product_id, data-roast_custom_options So i have added it using jquery 
check the code and your site. All the codesprovided by me working now.

--------------------------------------------------------------------*/

add_action('wp_footer','add_footer_script');
function add_footer_script(){
    ?>
    <script>
       jQuery('#roast_custom_options').on('change',function(){
           var roast_level = jQuery(this).val();
           /*console.log(roast_level); */
           var button = jQuery(this).closest('form').find('.add_to_cart_button'); console.log(button); 
           jQuery(button).attr('data-roast_custom_options',roast_level);
        });

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