如何为 Woocommerce 中的变体选项强制 "selected" 属性?

How to force "selected" attribute for variation options in Woocommerce?

我正在为我的一位客户开发 Woocommerce 主题。 对于这个项目,我需要克隆购物车表单(在产品页面上)以便将其显示在页面上的另一个地方。 我设法用这段代码做到了这一点:

$(document).on( 'found_variation', 'form.cart', function( event, variation ) { // found_variation // woocommerce_variation_select_change
    $('.fixed-price-right').empty();
    $(this).clone().appendTo( '.fixed-price-right' ).each(function() {
        $('.product-fixi').scrollToFixed();             
    });     
});

首先,在每个变体更改时,我清空将显示表单克隆的 div。 然后,我克隆它并修复了容器 div。

问题是除了选定的变化值,我得到了所有的东西。 实际上,默认选择值有这个属性:selected="selected"。但此属性不适用于其他选项。 你可以在这里看到一个活生生的例子:http://www.pro4mance.com.au/product/produrance-energy-gels-2/

如果我从克隆的表单提交,产品会被添加但没有选项。

奇怪的是,如果我在克隆表单的正确选项中手动(从 Web 控制台)添加此属性,然后将产品添加到购物车,则该产品会添加所有好的选项。

我真的不知道如何在每次更改时强制添加 selected="selected"。有人可以帮我管理吗?

谢谢大家!

我认为您将不得不查看 WooCommerce templates 文件夹中的文件 cart.php。使用它来创建您自己的自定义购物车文件。只需 运行 第二次循环即可获得您想要的内容,直接从服务器传送。参考:WordPress -- "the Loop" 您感兴趣的实际代码行是 foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) { 对于 WooCommerce 购物车,这是 "loop" 的顶部。再次添加该行,使用您自己的自定义来匹配您想要的购物车内容的第二个副本...

我建议将 jQuery 排除在外...

您显然不想直接在 WooCommerce 包中附加(以防将来更新)...(此处更新!)

哇,这看起来很简单...

WooCommerce (and almost all add-ons) provides a templating system. This means that every element displayed on a WooCommerce page can be overridden.

This system’s advantage is that you can modify the display of an element without editing WooCommerce core files (which is absolutely NOT recommended, if you do so, all your modifications will be lost at the next WooCommerce update, so just don’t do it). All templates are located in a woocommerce/templates folder. As explained in our documentation, all you have to do is to create a woocommerce folder within your theme’s directory, and in this folder duplicate the files you’d like to override. Please note that we strongly recommend using a child theme in order not to lose any modifications during your theme update.

对于需要在 Woocommerce 选项变量上强制添加 "selected" 属性的每个人,我是这样做的(使用 jQuery):

$('form.cart').on( 'change', '.variations select', function( event ) {
    $val=$(this).val();
    $(this).children('option').each(function(){
        $childVal = $(this).val(); 
        if ( $childVal == $val ) {
            $(this).attr('selected', 'selected');
        } else {
            $(this).removeAttr('selected');
        }   
    });
});

随时改进它(这可能不是最好的方法)。