【问题标题】:How to add and set a new default (active) product tab on the WooCommerce product page?如何在 WooCommerce 产品页面上添加和设置新的默认(活动)产品选项卡?
【发布时间】:2021-06-20 10:18:39
【问题描述】:

我在 WordPress 平台下使用 WooCommerce 插件,我正在尝试更改 single-product.php 页面中的默认选项卡。

Link to my website

所以现在我有第二个选项卡处于活动状态,我想将第一个选项卡更改为默认活动选项卡。

我已经使用 woocommerce_product_tabs 过滤钩更改了优先级:

add_filter('woocommerce_product_tabs', function($tabs) {
    global $post, $product;  // Access to the current product or post
    
    $custom_tab_title = get_field('props', $post->ID);
    $tabs['reviews']['priority'] = 10;
    if (!empty($custom_tab_title)) {
        $tabs['awp-' . sanitize_title('props')] = [
            'title' => 'אביזרים',
            'callback' => 'awp_custom_woocommerce_tabs',
            'priority' => 5
        ];
    }
    return $tabs;
});

我还尝试使用基于 active 类的 jQuery 更改它,如下所示:

jQuery(document).ready(function($){
    console.log( "ready!" );
    jQuery('.reviews_tab').removeClass('active');
jQuery('#tab-title-awp-props').addClass('active');
});

到目前为止没有任何效果。

如何更改 WooCommerce 单个产品页面中的默认活动选项卡?

【问题讨论】:

  • 可以尝试触发点击事件:jQuery('#tab-title-awp-props').trigger('click');
  • @David 很遗憾没有奏效。当我使用 lighthouse 跟踪页面加载过程时,我看到页面在标签真正加载之前就准备好了,所以它影响了 javascript 功能。

标签: javascript php jquery wordpress woocommerce


【解决方案1】:

您使用的 woocommerce_product_tabs 钩子是正确的,功能也是正确的。在模板内部使用:/woocommerce/single-product/tabs/tabs.php

但是,回调函数不见了。

你可以在这里找到完整的例子:

要将新产品标签设置为默认值,您需要使用以下(完整)代码:

// adds and sets a new default product tab on the product page
add_filter('woocommerce_product_tabs', 'add_new_default_product_tab' );
function add_new_default_product_tab( $tabs ) {

    global $product;

    // set the new priority to the "reviews" tab
    $tabs['reviews']['priority'] = 10;

    // gets the value to use as the title and slug of the new tab
    $custom_tab_title = get_field( 'props', $product->get_id() );

    // if the custom field is set, it adds the new tab
    if ( ! empty($custom_tab_title) ) {
        $tabs['awp-' . sanitize_title($custom_tab_title)] = array(
            'title' => 'אביזרים',
            'callback' => 'awp_custom_woocommerce_tabs',
            'priority' => 5
        );
    }
    return $tabs;
}


// create the content of the new tab
function awp_custom_woocommerce_tabs() {

    // the new tab content

}

props 假定为通过 ACF(高级自定义字段)插件添加的自定义字段。

代码已经过测试并且可以运行。将其添加到活动主题的 functions.php 中。

【讨论】:

  • 您好,谢谢您的回答。虽然有些东西仍然丢失,但我似乎无法让它工作。由于$custom_tab_title 返回希伯来语值,jquery 返回错误,所以我将其改回道具。但我仍然让第二个选项卡默认处于活动状态。这是为什么呢?
  • 没有注意到 URL 中有 #reviews 以某种方式.. 所以它总是将我重定向到评论。
猜你喜欢
  • 2018-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-23
  • 1970-01-01
相关资源
最近更新 更多