#php #wordpress #tabs #woocommerce #product
#php #wordpress #вкладки #woocommerce #продукт
Вопрос:
Я пытаюсь добавить три пользовательские вкладки в WooCommerce. У меня есть приведенный ниже код, и два из них отображаются, но по какой-то причине вкладка описания атрибута не отображается на странице. Мало того, что на вкладке количественных цен не отображается его описание. Я попытался переместить разные разделы кода в разные места и проверил код на наличие ошибок или недостающих разделов. Это настолько близко, насколько я могу понять.
Мой процесс заключается в основном в удалении существующих вкладок, которые мне не нужны, а затем в добавлении новых в том порядке, в котором я хочу, чтобы они появлялись.
У меня такое чувство, что я чего-то не хватает.
Вы можете посмотреть сайт здесь: http://demo.bergdahl.com/product/6-oz-catridge /
Вот код, который я использую:
// WooCommerce Tabs
// REMOVE EXISTING TABS
add_filter( 'woocommerce_product_tabs', 'woo_remove_product_tabs', 98 );
function woo_remove_product_tabs( $tabs ) {
unset( $tabs['description'] ); // Remove the description tab
// unset( $tabs['reviews'] ); // Remove the reviews tab
unset( $tabs['additional_information'] ); // Remove the additional information tab
return $tabs;
}
// ADD ATTRIBUTE DESCRIPTION TAB
add_filter( 'woocommerce_product_tabs', 'woo_attrib_desc_tab' );
function woo_attrib_desc_tab( $tabs ) {
// Adds the Attribute Description tab
$tabs['attrib_desc_tab'] = array(
'title' => __( 'Desc', 'woocommerce' ),
'priority' => 100,
'callback' => 'woo_attrib_desc_tab_content'
);
return $tabs;
}
// ADD QUANTITY PRICING TAB
add_filter( 'woocommerce_product_tabs', 'woo_qty_pricing_tab' );
function woo_qty_pricing_tab( $tabs ) {
// Adds the qty pricing tab
$tabs['qty_pricing_tab'] = array(
'title' => __( 'Quantity Pricing', 'woocommerce' ),
'priority' => 110,
'callback' => 'woo_qty_pricing_tab_content'
);
return $tabs;
}
// ADD OTHER PRODUCTS TAB
add_filter( 'woocommerce_product_tabs', 'woo_other_products_tab' );
function woo_other_products_tab( $tabs ) {
// Adds the other products tab
$tabs['other_products_tab'] = array(
'title' => __( 'Other Products', 'woocommerce' ),
'priority' => 120,
'callback' => 'woo_other_products_tab_content'
);
return $tabs;
}
// ADD CUSTOM TAB DESCRIPTIONS
function woo_attrib_desc_tab_content() {
// The attribute description tab content
echo '<h2>Description</h2>';
echo '<p>Custom description tab.</p>';
}
function woo_qty_pricing_tab_content() {
// The qty pricing tab content
echo '<h2>Quantity Pricing</h2>';
echo '<p>Here's your quantity pricing tab.</p>';
}
function woo_other_products_tab_content() {
// The other products tab content
echo '<h2>Other Products</h2>';
echo '<p>Here's your other products tab.</p>';
}
Редактировать в соответствии с ответом от LoicTheAztec ниже, это весь мой functions.php досье. Я пробовал это с и без ?>
внизу:
<?php
add_theme_support( 'builder-3.0' );
add_theme_support( 'builder-responsive' );
function register_my_fonts() {
wp_register_style('googleFonts-OpenSans', '//fonts.googleapis.com/css?family=Open Sans:400,300,700');
wp_enqueue_style( 'googleFonts-OpenSans');
}
add_action('wp_enqueue_scripts', 'register_my_fonts');
function sc_replacecolon( $content ){ return str_replace( '[sc:', '[sc name=', $content ); }
add_filter( 'the_content', 'sc_replacecolon', 5 );
/* WOOCOMMERCE */
add_filter( 'woocommerce_product_tabs', 'woo_custom_product_tabs', 100, 1 );
function woo_custom_product_tabs( $tabs ) {
// 1) Removing tabs
unset( $tabs['description'] ); // Remove the description tab
// unset( $tabs['reviews'] ); // Remove the reviews tab
unset( $tabs['additional_information'] ); // Remove the additional information tab
// 2 Adding new tabs
//Attribute Description tab
$tabs['attrib_desc_tab'] = array(
'title' => __( 'Desc', 'woocommerce' ),
'priority' => 100,
'callback' => 'woo_attrib_desc_tab_content'
);
// Adds the qty pricing tab
$tabs['qty_pricing_tab'] = array(
'title' => __( 'Quantity Pricing', 'woocommerce' ),
'priority' => 110,
'callback' => 'woo_qty_pricing_tab_content'
);
// Adds the other products tab
$tabs['other_products_tab'] = array(
'title' => __( 'Other Products', 'woocommerce' ),
'priority' => 120,
'callback' => 'woo_other_products_tab_content'
);
return $tabs;
}
// New Tab contents
function woo_attrib_desc_tab_content() {
// The attribute description tab content
echo '<h2>Description</h2>';
echo '<p>Custom description tab.</p>';
}
function woo_qty_pricing_tab_content() {
// The qty pricing tab content
echo '<h2>Quantity Pricing</h2>';
echo '<p>Here's your quantity pricing tab.</p>';
}
function woo_other_products_tab_content() {
// The other products tab content
echo '<h2>Other Products</h2>';
echo '<p>Here's your other products tab.</p>';
}
?>
Комментарии:
1. «Это сломало сайт» в 95% случаев является синтаксической ошибкой. Вы можете получить более полезное описание ошибки, включив
WP_DEBUG
.2. Я добавил приведенный ниже код Loic в начало моего functions.php и получаем: Ошибка синтаксического анализа: синтаксическая ошибка, неожиданный ‘add_filter’ (T_STRING) в /home/parkymay/public_html/demo/wp-content/themes/BuilderChild-Default/functions.php в строке 1
3. Ошибка указывает на то, что она находится в строке 1, что, если я должен был догадаться, указывает на проблему с родительской темой
functions.php
. Я использовал всю вашуfunctions.php
тему сверху в качестве дочерней темы Twenty Sixteen, и она не выдает никаких ошибок.4. Можете ли вы удалить все из родительского
functions.php
файла, а затем добавить его обратно по 1 функции за раз?5. helgatheviking, я придумал обходной путь. Я добавил код в custom-functions.php файл в родительской теме и удалил все ссылки на него в дочерней теме. Родительский functions.php файл, уже вызванный для пользовательского файла, если он существовал, так что он отлично работал! Спасибо за ваши предложения, они действительно помогли отследить проблемы.
Ответ №1:
Поскольку вы используете 4 раза один и тот же хук woocommerce_product_tabs
, ваша проблема связана с наивысшим приоритетом для первого. Вместо этого вы должны использовать его только один раз, объединив эти 4 подключенные функции в одну.
Вот ваш функциональный протестированный код, немного измененный:
add_filter( 'woocommerce_product_tabs', 'woo_custom_product_tabs' );
function woo_custom_product_tabs( $tabs ) {
// 1) Removing tabs
unset( $tabs['description'] ); // Remove the description tab
// unset( $tabs['reviews'] ); // Remove the reviews tab
unset( $tabs['additional_information'] ); // Remove the additional information tab
// 2 Adding new tabs and set the right order
//Attribute Description tab
$tabs['attrib_desc_tab'] = array(
'title' => __( 'Desc', 'woocommerce' ),
'priority' => 100,
'callback' => 'woo_attrib_desc_tab_content'
);
// Adds the qty pricing tab
$tabs['qty_pricing_tab'] = array(
'title' => __( 'Quantity Pricing', 'woocommerce' ),
'priority' => 110,
'callback' => 'woo_qty_pricing_tab_content'
);
// Adds the other products tab
$tabs['other_products_tab'] = array(
'title' => __( 'Other Products', 'woocommerce' ),
'priority' => 120,
'callback' => 'woo_other_products_tab_content'
);
return $tabs;
}
// New Tab contents
function woo_attrib_desc_tab_content() {
// The attribute description tab content
echo '<h2>Description</h2>';
echo '<p>Custom description tab.</p>';
}
function woo_qty_pricing_tab_content() {
// The qty pricing tab content
echo '<h2>Quantity Pricing</h2>';
echo '<p>Here's your quantity pricing tab.</p>';
}
function woo_other_products_tab_content() {
// The other products tab content
echo '<h2>Other Products</h2>';
echo '<p>Here's your other products tab.</p>';
}
Этот код входит function.php файл вашей активной дочерней темы (или темы) или также в любом файле плагина.
Протестировано и работает.
С помощью того же хука вы можете:
- Удаление вкладок
- Добавление вкладок
- Изменение порядка вкладок
Соответствующая официальная документация: редактирование вкладок данных продукта
Комментарии:
1. Проверил это, и у меня это работает (не думаю, что вам нужен приоритет 100, но это ничему не вредит), так что, вероятно, где-то еще в вашем есть синтаксическая ошибка
functions.php
. Как я советовал выше, вы должны включитьWP_DEBUG
, чтобы узнать, где.
Ответ №2:
Единственное дополнение, которое я сделал, это проверить, существует ли контент на вкладке, прежде чем добавлять его. Я просто обернул каждый новый массив с помощью оператора ‘if’.
if (!empty(get_the_content())) {
$tabs['tab'] = array(
'title' => __( 'Tab Title', 'woocommerce' ),
'priority' => 100,
'callback' => 'woo_tab_content'
);
}
Ответ №3:
function my_simple_custom_product_tab( $tabs ) {
$tabs['my_custom_tab'] = array(
'title' => __( 'Custom Tab', 'textdomain' ),
'callback' => 'my_simple_custom_tab_content',
'priority' => 50,
);
return $tabs;
}
add_filter( 'woocommerce_product_tabs', 'my_simple_custom_product_tab' );
/**
* Function that displays output for the shipping tab.
*/
function my_simple_custom_tab_content( $slug, $tab ) {
?><h2><?php echo wp_kses_post( $tab['title'] ); ?></h2>
<p>Tab Content</p><?php
}