RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / user-371447

Dmitry's questions

Martin Hope
Dmitry
Asked: 2024-09-23 07:26:07 +0000 UTC

WooCommerce 产品列表中定义的属性

  • 5

在 WooCommerce 在线商店中,我使用在存档/类别页面上显示某些产品属性的代码。

add_action( 'woocommerce_before_shop_loop_item_title', 'new_template_loop_product_meta', 20 );
function new_template_loop_product_meta() {
    global $product;

    $attrs_by_cats = [
        20 => [ 'pa_size' ],

    ];

    $attr_list = [
        'Размер'        => 'pa_size',
    ];

    if ( ! is_object( $product ) ) {
        $product = wc_get_product( get_the_id() );
    }

    $cats = $product->get_category_ids();

    if ( ! is_array( $cats ) ) {
        return;
    }

    $attrs = [];

    foreach ( $cats as $cat ) {
        if ( isset( $attrs_by_cats[ $cat ] ) ) {
            $attrs[] = $attrs_by_cats[ $cat ];
        }
    }

    $allowed_attrs = array_unique( array_merge( [], ...$attrs ) );

    echo '<div class="">';

    foreach ( $attr_list as $attr_title => $attr_name ) {
        if ( in_array( $attr_name, $allowed_attrs, true ) ) {
            show_attribute( $product, $attr_title, $attr_name );
        }
    }

    echo '</div>';
}
function show_attribute( $product, $attr_title, $attr_name ) {
    if ( 'sku' === $attr_name ) {
        $attr = (string) $product->get_sku();
    } else {
        $attr = $product->get_attribute( $attr_name );
    }

    if ( '' === $attr ) {
        return;
    }

    echo '<span class="">' . esc_html( $attr ) . '</span>';
}

目前,代码在一个列表/数组中显示“Size”属性,并用逗号分隔。我想单独显示尺寸且不带逗号,即将每个尺寸包裹在一个跨度中,而不是全部包裹在一起。

如何实施?我很乐意帮助您编写代码!

php
  • 1 个回答
  • 19 Views
Martin Hope
Dmitry
Asked: 2022-08-26 19:18:45 +0000 UTC

根据 WooCommerce 中的填充字段更新运输方式

  • 2

在我的在线商店中,有两种标准送货方式统一费率和免费送货。我添加了一个按距离运送的插件。

因此,当客户在下订单时填写“城市”和“地址”字段时,应添加新的交付方式。但在您选择统一费率或免费送货之前,新的送货是不可见的。

据我了解,我没有根据填写的字段自动更新运输方式。

接下来,我使用了这段代码:

add_action('wp_footer', 'woocommerce_custom_update_checkout', 50);
function woocommerce_custom_update_checkout() {
    if (is_checkout()) {
    ?>
    <script type="text/javascript">
        jQuery( document ).ready(function( $ ) {            
            $('#billing_address_1').click(function(){
                jQuery('body').trigger('update_checkout', { update_shipping_method: true });
            });

        });
    </script>
    <?php
    }
}

但是,直到我第二次单击填写的字段,运输方式才更新。

是否可以将 AJAX 连接到此代码,以便立即看到结果,以免两次单击填充的字段?

php
  • 2 个回答
  • 10 Views
Martin Hope
Dmitry
Asked: 2022-04-29 01:59:27 +0000 UTC

将标准 WooCommerce 产品小部件添加到博客文章时出错

  • 0

我正在使用代码来更改添加到购物车的项目的“添加到购物车”按钮的文本和样式。

/* Меняем текст кнопки добавления в корзину для каталога и категорий */
add_filter( 'woocommerce_product_add_to_cart_text', 'new_products_button_text', 20, 2 );
 
function new_products_button_text( $text, $product ) {
 
    if( 
       $product->is_type( 'simple' )
       && $product->is_purchasable()
       && $product->is_in_stock()
       && WC()->cart->find_product_in_cart( WC()->cart->generate_cart_id( $product->get_id() ) )
    ) { 
        $text = 'В корзине'; 
    }
 
    return $text;
 
}

/* Меняем текст кнопки добавления в корзину для страницы товара */
add_filter( 'woocommerce_product_single_add_to_cart_text', 'new_single_product_button_text' );
 
function new_single_product_button_text( $text ) {
 
    if( WC()->cart->find_product_in_cart( WC()->cart->generate_cart_id( get_the_ID() ) ) ) {
        $text = 'В корзине';
    }
 
    return $text;
 
}

add_action( 'wp_footer', 'action_wp_footer' );
function action_wp_footer() {
    ?>
    <script>
        jQuery(document).ready(function($) {
            var selector = '.add_to_cart_text:contains("В корзине")';           
            
            // Selector contains specific text
            if ( $( selector ).length > 0 ) {
                $( selector ).addClass( 'product-is-added' );
            } else {
                $( selector ).removeClass( 'product-is-added' );            
            }
            
        });
    </script>
    <?php
}

add_action( 'wp_footer', 'ajax_button_text_js_script' );
function ajax_button_text_js_script() {
    $text = __('В корзине', 'woocommerce');
    ?>
    <script>
        jQuery(function($) {
            var text = '<?php echo $text; ?>',      $this;

            $(document.body).on('click', '.ajax_add_to_cart', function(event){
                $this = $(this); // Get button jQuery Object and set it in a variable
            });

            $(document.body).on('added_to_cart', function(event,b,data){
                var buttonText = '<span class="add_to_cart_text product-is-added">'+text+'</span><i class="cart-icon pe-7s-cart"></i>';

                // Change inner button html (with text) and Change "data-tip" attribute value
                $this.html(buttonText).attr('data-tip',text);
            });
        });
    </script>
    <?php
}

代码本身可以正常工作,但是博客中存在问题。创建博客文章时,我使用 WPBakery Page Builder 可视化编辑器。我还在博客文章中添加了一个带有产品的标准 WooCommerce 小部件。

使用标准 WooCommerce 小部件发布或保存帖子时,我收到一个致命错误:

致命错误:未捕获错误:在 /public_html/wp-content/themes/functions.php:703 中调用成员函数 find_product_in_cart() 堆栈跟踪:#0 /public_html/wp-includes/class-wp-hook.php (292): new_products_button_text('\xD0\x92 \xD0\xBA\xD0\xBE\xD1\x80\xD0\xB7\xD0\xB8\xD0\xBD...', 对象(WC_Product_Simple)) #1 /public_html/ wp-includes/plugin.php(212): WP_Hook->apply_filters('\xD0\x92\xD0\xBA\xD0\xBE\xD1\x80\xD0\xB7\xD0\xB8\xD0\xBD...',数组)#2 /public_html/wp-content/plugins/woocommerce/includes/class-wc-product-simple.php(62): apply_filters('woocommerce_pro...', '\xD0\x92 \xD0\xBA\xD0 \xBE\xD1\x80\xD0\xB7\xD0\xB8\xD0\xBD...',对象(WC_Product_Simple))#3 /public_html/wp-content/themes/cores/nasa-woo-functions.php(393 ): WC_Product_Simple->add_to_cart_text() #4 /public_html/wp-content/themes/cores/nasa-woo- in /public_html/wp-content/themes/functions.php 在第 703 行

如果没有产品小部件,则帖子发布时不会出现问题。

第 703 行是上述代码的一部分:

&& WC()->cart->find_product_in_cart( WC()->cart->generate_cart_id( $product->get_id() ) )

告诉我可能是什么问题以及如何解决?

php
  • 1 个回答
  • 10 Views
Martin Hope
Dmitry
Asked: 2022-04-15 02:59:04 +0000 UTC

如果没有添加 WooCommerce 产品,则禁用产品页面上的选项卡

  • 1

我正在使用在单独的产品页面上显示“相关产品”选项卡的代码。

// Display a multiselect field in "Linked Products" section
add_action( 'woocommerce_product_options_related', 'display_handles_product_field' );
function display_handles_product_field() {
    global $product_object, $post;
    ?>
    <h2><strong>Сопутствующие товары во вкладках</strong></h2>
    <p class="form-field">
        <label for="handles_product"><?php _e( 'Сопутствующие товары', 'woocommerce' ); ?></label>
        <select class="wc-product-search" multiple="multiple" id="handles_product_ids" name="_handles_product_ids[]" data-placeholder="<?php esc_attr_e( 'Search for a product&hellip;', 'woocommerce' ); ?>" data-action="woocommerce_json_search_products_and_variations" data-exclude="<?php echo intval( $post->ID ); ?>">
            <?php
                $product_ids = $product_object->get_meta( '_handles_product_ids' );

                foreach ( $product_ids as $product_id ) {
                    $product = wc_get_product( $product_id );
                    if ( is_object( $product ) ) {
                        echo '<option value="' . esc_attr( $product_id ) . '"' . selected( true, true, false ) . '>' . wp_kses_post( $product->get_formatted_name() ) . '</option>';
                    }
                }
            ?>
        </select>
    </p>
    <?php
}

// Save the values to the product
add_action( 'woocommerce_admin_process_product_object', 'save_handles_product_field_value', 10, 1 );
function save_handles_product_field_value( $product ){
    $data = isset( $_POST['_handles_product_ids'] ) ? array_map( 'intval', (array) $_POST['_handles_product_ids'] ) : array();
    $product->update_meta_data( '_handles_product_ids', $data );
}


/* New Handles Product Tab */
add_filter( 'woocommerce_product_tabs', 'new_handles_product_tab' );
function new_handles_product_tab( $tabs ) {
    
    /* Add new tab */
    $tabs['new_handles_product_tab'] = array(
        'title'     => __( 'Сопутствующие товары', 'woocommerce' ),
        'priority'  => 50,
        'callback'  => 'new_handles_product_tab_content'
    );

    return $tabs;

}

function new_handles_product_tab_content() {
    global $product;
    
    $product_ids = $product->get_meta( '_handles_product_ids' ); // Get handles
    
    if( ! empty($product_ids) )
        $product_ids = implode(',', $product_ids);
        
        echo do_shortcode( "[products ids='$product_ids' columns='4']" ); // Using [products] shortcode for display.
}

代码可以运行,但是有一个小问题。如果“相关”选项卡中没有手动添加的产品,则显示所有商店产品。

告诉我如何解决这个问题?如果标签中没有添加的产品,我该如何禁用它?

php
  • 1 个回答
  • 10 Views
Martin Hope
Dmitry
Asked: 2022-02-07 09:17:24 +0000 UTC

WooCommerce 中的运输方式工具提示

  • 0

我需要在统一费率交付选项旁边放置一个工具提示,一个问号图标,以便单击时会弹出一个窗口,其中包含交付条件的描述。

我有一些代码显示一个图标(现在将其替换为文本“我的图标”),单击时会弹出一个窗口。

function action_woocommerce_after_shipping_rate( $method, $index ) {
    
    // Compare (adjust as needed)
    if( $method->get_id() == 'flat_rate:1' ) {
        echo '<span class="popup" onclick="myFunction()">My Icon<span class="popuptext" id="myPopup">';
        echo dynamic_sidebar( 'tooltip_sidebar' );          
        echo '</span></span>';
    }
}
add_action( 'woocommerce_after_shipping_rate', 'action_woocommerce_after_shipping_rate', 10, 2 ); 

弹出脚本:

<script>
// When the user clicks on <div>, open the popup
function myFunction() {
  var popup = document.getElementById("myPopup");
  popup.classList.toggle("show");
}
</script>

弹出窗口的样式:

/* Popup container */
.popup {
    position: relative;
    display: inline-block;
    cursor: pointer;
}

/* The actual popup (appears on top) */
.popup .popuptext {
    visibility: hidden;
    width: 320px;
    background: #fff;
    color: #222;
    text-align: center; 
    padding: 10px;
    position: absolute;
    z-index: 1;
    bottom: 125%;
    left: 50%;
    -webkit-box-shadow: 0px 5px 15px 0px rgba(50, 50, 50, 0.3);
    -moz-box-shadow: 0px 5px 15px 0px rgba(50, 50, 50, 0.3);
    box-shadow: 0px 5px 15px 0px rgba(50, 50, 50, 0.3);
}

/* Popup arrow */
.popup .popuptext::after {
    content: "X";
    position: absolute;
    top: 0;
    right: 5%;
    border-width: 5px;
    border-style: solid;
    border-color: #fff transparent transparent transparent;
}

/* Toggle this class when clicking on the popup container (hide and show the popup) */
.popup .show {
    visibility: visible;
    -webkit-animation: fadeIn 1s;
    animation: fadeIn 1s
}

/* Add animation (fade in the popup) */
@-webkit-keyframes fadeIn {
    from {opacity: 0;}
    to {opacity: 1;}
}

@keyframes fadeIn {
    from {opacity: 0;}
    to {opacity:1 ;}
}

我还为侧边栏注册了一个新区域,其中显示了交货条件:

add_action( 'widgets_init', 'register_new_sidebar' );
function register_new_sidebar() {

    register_sidebar(
        array(
            'id' => 'tooltip_sidebar',
            'name' => 'Условия доставки',
            'description' => 'Добавьте ваши условия доставки',
            'before_widget' => '<div>',
            'after_widget' => '</div>',
            'before_title' => '<h3 class="widget-title">',
            'after_title' => '</h3>'
        )
    );
}

但是这里出现了一个问题。在带有交货条款的文本下,会出现一个数字1,尽管它根本不在文本中。最有可能的是,这由侧边栏本身的 id 或侧边栏列的编号显示。

显然我错误地添加了侧边栏输出echo dynamic_sidebar ('tooltip_sidebar');。也许您需要为此侧边栏的输出添加条件?

虽然这还不是全部。在结帐页面上,弹出窗口显示交货条件的文本和数量1。但是在购物篮页面上,只显示一个数字,没有交货条件的文字。但是从钩子来看,两个页面上的文本应该显示相同。

请告诉我如何解决这个问题?

php
  • 1 个回答
  • 10 Views
Martin Hope
Dmitry
Asked: 2022-01-07 08:09:57 +0000 UTC

对于每个类别,在 WooCommerce 的存档/类别页面上的产品列表中显示其属性

  • 2

有一个代码可以在存档/类别页面上显示指定的产品属性。

/* Show product attributes */
add_action( 'woocommerce_after_shop_loop_item', 'new_template_loop_product_meta', 20 );

function new_template_loop_product_meta() {
    global $product;

    $attr_list = [
        'Brand'        => 'pa_brand',
        'Country'      => 'pa_country',
        'SKU'          => 'sku',
        'Material'     => 'pa_material',
        'Type'         => 'pa_product_type',
        'Color'        => 'pa_color',
        'Size'         => 'pa_size',
        'Model'        => 'pa_model',
        'Collection'   => 'pa_collection',
        'Mechanism'    => 'pa_mechanism',
        'Magnetic'     => 'pa_magnetic',
        'Side'         => 'pa_side',
        'Load'         => 'pa_load',
        'Availability' => 'pa_availability',
    ];

    if ( ! is_object( $product ) ) {
        $product = wc_get_product( get_the_id() );
    }

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

    foreach ( $attr_list as $attr_title => $attr_name ) {
        show_attribute( $product, $attr_title, $attr_name );
    }

    echo '</div>';
}

/**
 * Show attribute.
 *
 * @param WC_Product $product    Product.
 * @param string     $attr_title Attribute title.
 * @param string     $attr_name  Attribute name.
 */
function show_attribute( $product, $attr_title, $attr_name ) {
    if ( 'sku' === $attr_name ) {
        $attr = (string) $product->get_sku();
    } else {
        $attr = $product->get_attribute( $attr_name );
    }

    if ( '' === $attr ) {
        return;
    }

    echo '<span>' . esc_html( $attr_title ) . ': </span><span class="pa-right">' . esc_html( $attr ) . '</span><br />';
}

还有一些产品类别,您只需要显示代码中列出的某些属性。

例如,在“A 类”产品列表中,您需要显示属性pa_brand, pa_country。在“B 类”产品列表中,您需要显示属性pa_brand, pa_model等。

据我了解,您需要指定类别 ID $cat_id = 197;,并且$cat_ids = $product->get_category_ids(); 为每个类别设置您自己的产品属性列表。

但是如何将所有这些组合成一个代码呢?告诉我如何做到这一点?我认为其他用户也会发现这个答案也很有用。

我会很高兴你的帮助!

php
  • 1 个回答
  • 10 Views
Martin Hope
Dmitry
Asked: 2022-01-02 01:55:55 +0000 UTC

在 WooCommerce 中的存档和类别页面上显示设置的产品属性

  • 0

我在存档和类别页面上显示了产品属性。

add_action( 'woocommerce_after_shop_loop_item', 'new_template_loop_product_meta', 20 );
function new_template_loop_product_meta() {
    global $product;
    
    if( ! is_object( $product ) ) { 
        $product = wc_get_product( get_the_id() );
        $sku = $product->get_sku();
    }

    echo '<div class="pa">';
    echo '<span>Brand: </span>' . '<span class="pa-right">' . $product->get_attribute('pa_brand') . '</span><br />';
    echo '<span>Country: </span>' . '<span class="pa-right">' . $product->get_attribute('pa_contry') . '</span><br />';
    echo '<span>SKU: </span>' . '<span class="pa-right">' . $product->get_sku() . '</span><br />';
    echo '<span>Material: </span>' . '<span class="pa-right">' . $product->get_attribute('pa_material') . '</span><br />';
    echo '<span>Type: </span>' . '<span class="pa-right">' . $product->get_attribute('pa_product_type') . '</span><br />';
    echo '<span>Color: </span>' . '<span class="pa-right">' . $product->get_attribute('pa_color') . '</span><br />';
    echo '<span>Size: </span>' . '<span class="pa-right">' . $product->get_attribute('pa_size') . '</span><br />';
    echo '<span>Model: </span>' . '<span class="pa-right">' . $product->get_attribute('pa_model') . '</span><br />';
    echo '<span>Collection: </span>' . '<span class="pa-right">' . $product->get_attribute('pa_collection') . '</span><br />';
    echo '<span>Mechanism: </span>' . '<span class="pa-right">' . $product->get_attribute('pa_mechanism') . '</span><br />';
    echo '<span>Magnetic: </span>' . '<span class="pa-right">' . $product->get_attribute('pa_magnetic') . '</span><br />';
    echo '<span>Side: </span>' . '<span class="pa-right">' . $product->get_attribute('pa_side') . '</span><br />';
    echo '<span>Load: </span>' . '<span class="pa-right">' . $product->get_attribute('pa_load') . '</span><br />';
    echo '<span>Availability: </span>' . '<span class="pa-right">' . $product->get_attribute('pa_availability') . '</span>';
    echo '</div>';
}

但是这些页面按原样显示所有属性的名称。告诉我,我怎样才能只显示为特定产品设置的那些属性?

这可能是第二个问题。优化代码的最佳方法是什么,以便对具有如此多属性的 Base 没有不必要的请求。

我会很高兴你的帮助!

php
  • 1 个回答
  • 10 Views
Martin Hope
Dmitry
Asked: 2021-12-23 00:50:16 +0000 UTC

在 WooCommerce 中创建产品名称时自动替换产品名称中的类别

  • 1

在我目前在 WooCommerce 上开发的网站上,产品链接显示如下:

https://example.com/handles/roset/pasini/0031-cr-sat

告诉我,如何在创建产品名称时自动将这些类别替换为产品名称?

例如,如果我写产品名称0031 CR SAT,结果应该是Handles Roset Pasini 0031 CR SAT。怎么做?

我只是找不到正确的代码和问题的答案。我什至不知道从哪里开始,这就是为什么我的问题中没有源代码。

如果你能帮忙,我会很高兴的!

php
  • 1 个回答
  • 10 Views
Martin Hope
Dmitry
Asked: 2020-02-19 12:23:28 +0000 UTC

在 WooCommerce 中的新行上显示每个类别及其产品

  • 2

在商店的主页上,我使用了一个代码来显示此类产品的类别名称:

第一类

产品 1 产品 2 产品 3

第 2 类

产品 1 产品 2 产品 3

我将此代码添加到子主题的 archive-product.php 文件中:

defined( 'ABSPATH' ) || exit;

get_header( 'shop' );

/**
* Hook: woocommerce_before_main_content.
*
* @hooked woocommerce_output_content_wrapper - 10 (outputs opening divs for the content)
* @hooked woocommerce_breadcrumb - 20
* @hooked WC_Structured_Data::generate_website_data() - 30
*/
do_action( 'woocommerce_before_main_content' );

if ( woocommerce_product_loop() ) {

    /**
    * Hook: woocommerce_before_shop_loop.
    *
    * @hooked wc_print_notices - 10
    * @hooked woocommerce_result_count - 20
    * @hooked woocommerce_catalog_ordering - 30
    */
    do_action( 'woocommerce_before_shop_loop' );

    woocommerce_product_loop_start();

    if ( wc_get_loop_prop( 'total' ) ) {

            /* Start my loop section */
            foreach( get_terms( array( 'taxonomy' => 'product_cat' ) ) as $category ) :
                $products_loop = new WP_Query( array(
                    'post_type' => 'product',

                    'showposts' => -1,

                    'tax_query' => array_merge( array(
                        'relation'  => 'AND',
                        array(
                            'taxonomy' => 'product_cat',
                            'terms'    => array( $category->term_id ),
                            'field'   => 'term_id'
                        )
                    ), WC()->query->get_tax_query() ),

                    'meta_query' => array_merge( array(

                    // You can optionally add extra meta queries here

                ), WC()->query->get_meta_query() )
            ) );

            ?>                      

            <h2 data-link="<?php echo get_term_link( (int) $category->term_id, 'product_cat' ); ?>"><?php echo $category->name; ?></h2>

            <?php
                while ( $products_loop->have_posts() ) {
                    $products_loop->the_post();
                    /**
                    * woocommerce_shop_loop hook.
                    *
                    * @hooked WC_Structured_Data::generate_product_data() - 10
                    */
                    do_action( 'woocommerce_shop_loop' );
                    wc_get_template_part( 'content', 'product' );
                }
                wp_reset_postdata();
            endforeach;
            /* End my loop section */

    }

    woocommerce_product_loop_end();

    /**
    * Hook: woocommerce_after_shop_loop.
    *
    * @hooked woocommerce_pagination - 10
    */
    do_action( 'woocommerce_after_shop_loop' );
} else {
    /**
    * Hook: woocommerce_no_products_found.
    *
    * @hooked wc_no_products_found - 10
    */
    do_action( 'woocommerce_no_products_found' );
}

/**
* Hook: woocommerce_after_main_content.
*
* @hooked woocommerce_output_content_wrapper_end - 10 (outputs closing divs for the content)
*/
do_action( 'woocommerce_after_main_content' );

/**
* Hook: woocommerce_sidebar.
*
* @hooked woocommerce_get_sidebar - 10
*/
do_action( 'woocommerce_sidebar' );

get_footer( 'shop' );

但不幸的是,类别和产品并未按应有的方式显示。类别在一行上,但应显示在新行上。

这是文件中的代码还是样式有问题?如何解决这个问题?我会很高兴你的帮助!

php
  • 1 个回答
  • 10 Views
Martin Hope
Dmitry
Asked: 2020-02-09 22:33:23 +0000 UTC

在 WooCommerce 快速查看窗口中显示自定义选择表单

  • 1

我正在使用在创建/编辑产品页面上显示“烘焙级别”复选框的代码。当经理点击此复选框时,单个产品页面上会出现一个选择框,允许客户选择“烘焙级别”。

当您选择产品并将其添加到购物车时,所选值会显示在购物车本身中。此值也显示在管理面板的结帐页面、感谢页面、电子邮件通知和订单编辑页面上。

这是代码:

// 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 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());
    }
}   

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
}

我正在尝试在子主题的content-product-quick-view.php 文件中将“烘焙级别”选择表单添加到快速查看窗口。

添加代码时出现错误。要么不显示表单本身,要么“添加到购物车”按钮消失。

这是表单代码:

// If is single product page and have the "roast_checkbox" enabled we display the field
if ( $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>';
}

对于这个 PHP 文件,表单代码本身可能不正确或不完整。尽管操作是正确的,并且一切都在单独的产品页面上运行。我恳请您在这件事上提供帮助。

php
  • 1 个回答
  • 10 Views

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5