在WooCommerce中,我希望在标签旁边显示所选属性的名称.

<th class="label">
    <label for="<?php echo esc_attr( sanitize_title( $attribute_name ) ); ?>"><?php echo wc_attribute_label( $attribute_name ); // WPCS: XSS ok. ?></label> 
    <?php 
    $brand_terms = get_the_terms($post, 'pa_spieki');
    $brand_string = ''; // Reset string
    foreach ($brand_terms as $term) :
    $brand_string .= $term->name . ' ';
    endforeach;

    echo $brand_string;
    ?>
</th>

不幸的是,我的代码返回整个列表,而不仅仅是选定的属性.

enter image description here

我怎样才能改变这一点?

推荐答案

你不能用PHP在服务器端管理它,需要JavaScript.try 以下代码替换:

add_action('woocommerce_before_add_to_cart_form', 'display_specific_selected_attribute_term_name', 25);
function display_specific_selected_attribute_term_name() {
    global $product;

    if ( !$product->is_type('variable') ) {
        return; // Exit if it's not a variable product
    }

    $taxonomy = 'pa_spieki'; // <== HERE set the attribute taxonomy

    wc_enqueue_js("const selAttr = 'select#{$taxonomy}',  
        selAttrOption = selAttr+' option:selected', 
        selLabel = 'label[for={$taxonomy}]', 
        selSpan  = 'span.for-{$taxonomy}';
    
    $(selLabel).after(' <span class=\"for-{$taxonomy}\"></span>');

    function displayAttrSelectedOptionText(){
        const textValue = $(selAttr).val() != '' ? $(selAttrOption).text() : '';
        $(selSpan).text(textValue);
    }

    displayAttrSelectedOptionText();

    $('form.cart').on('change', 'select#{$taxonomy}', function() {
        displayAttrSelectedOptionText();
    })");
}

代码位于您的子主题的unctions.php文件中(或在插件中).经过测试,效果良好.

Php相关问答推荐

调用woocommerce_customer_Save_add动作挂钩时发生致命错误

在WooCommerce中执行一次银行电汇确认付款代码

在不超过PHP时间限制的情况下,在Laravel中高效地插入批量数据(25万条记录)?(队列、多租户)

有什么方法可以阻止WordPress主题升级通知吗?

将变体设置字段添加到WooCommerce中的特定变量产品

MySQLi是否在事务错误时删除保存点(并且仅删除保存点)?

如何限制WordPress自定义分类术语页面中的术语数量

在 PHP MySQL 中自动生成账单编号

向元素添加类时添加循环错误

我的功能以舒适的方式显示数组 struct

在WooCommerce可变产品中显示所选变体的自定义字段

Laravel的Storage::exists返回false,而file_exists返回true.

如何使用在产品快速编辑菜单前端的自定义框中 Select 的值更新 woocommerce 产品属性值?

如何使用动态变量定义 bind_result?

我怎样才能在 .htaccess 中有 2 个参数?

如何从此字符串创建 Carbon 对象:2022-06-21T05:52:46.648533678Z?

Laravel 查询关系是否为 bool

列表不在 GROUP BY 子句中并且包含 X2CRM 中的非聚合列

使用 GROUP_CONCAT 规范化/转置来自查询的数据

如何通过本地主机在同一台 PC 上同时运行 Microsoft IIS 和 WAMP