如何在 WooCommerce 产品页面上添加和设置新的默认(活动)产品选项卡?

时间:2021-03-23 17:51:23

标签: javascript php jquery wordpress woocommerce

我在 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 单个产品页面中的默认活动选项卡?

1 个答案:

答案 0 :(得分:2)

您使用的 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。