Пользовательский суффикс цены продукта на основе категорий продуктов в Woocommerce - PullRequest
0 голосов
/ 22 ноября 2018

Мне нужно добавить «за метр» к цене в большинстве моего онлайн-каталога, я пробовал код на этой теме в моем файле finctions.php, но не могу заставить его пропустить / включить определенные категории- кажется, все или ничего.Что я делаю неправильно?

Я отредактировал код следующим образом:

/*add 'per metre' after selected items*/
add_filter( 'woocommerce_get_price_html', 'conditional_price_suffix', 20, 2 );
function conditional_price_suffix( $price, $product ) {
    // HERE define your product categories (can be IDs, slugs or names)
    $product_categories = array('fabric','haberdashery', 'lining',);

    if( ! has_term( $product_categories, 'fasteners', 'patches', 'remnnants', $product->get_id() ) )
        $price .= ' ' . __('per metre');

    return $price;
}

Я хочу, чтобы «ткани», «галантерея», «подкладка» отображались на метр, а «застежки», «заплатки»,«остатки», чтобы НЕ показывать суффикс.

Я пробовал варианты исключений кода -my в верхнем бите и включений во второй части, с / без раздела "(! Has term", но в зависимости от того, что я делаю, принимает все сообщения суффиксапрочь или относится ко всем категориям.

Было бы удивительно, если бы я мог заставить это работать так, как ранее использовал очень раздутый плагин. Я только в основном способен на это, поэтому, пожалуйста, не стесняйтесьпоговорить со мной, как будто я идиот.

1 Ответ

0 голосов
/ 23 ноября 2018

В вашем коде есть небольшая ошибка в функции has_term().

Для обработки родительских категорий продуктов мы будем использовать пользовательскую условную функцию вместо has_tem().

Я также добавил некоторый код для обработки выбранной цены варианта продукта переменных продуктов, поэтому попробуйте это вместо:

// Custom conditional function that checks for parent product categories
function has_product_categories( $categories, $product_id ) {
     // Initializing
    $parent_term_ids = $categories_ids = array();
    $taxonomy        = 'product_cat';

    // Convert categories term names and slugs to categories term ids
    foreach ( $categories as $category ){
        if( is_numeric( $category ) ) {
            $categories_ids[] = (int) $category;
        } elseif ( term_exists( sanitize_title( $category ), $taxonomy ) ) {
            $categories_ids[] = get_term_by( 'slug', sanitize_title( $category ), $taxonomy )->term_id;
        }
    }

    // Loop through the current product category terms to get only parent main category term
    foreach( get_the_terms( $product_id, $taxonomy ) as $term ){
        if( $term->parent > 0 ){
            $parent_term_ids[] = $term->parent; // Set the parent product category
            $parent_term_ids[] = $term->term_id; // (and the child)
        } else {
            $parent_term_ids[] = $term->term_id; // It is the Main category term and we set it.
        }
    }
    return array_intersect( $categories_ids, array_unique($parent_term_ids) ) ? true : false;
}

add_filter( 'woocommerce_get_price_html', 'conditional_price_suffix', 10, 2 );
function conditional_price_suffix( $price, $product ) {
    // Handling product variations
    $product_id = $product->is_type('variation') ? $product->get_parent_id() : $product->get_id();

    // HERE define your product categories (can be IDs, slugs or names)
    $product_categories = array('fabric','haberdashery', 'lining');

    if( has_product_categories( $product_categories, $product_id ) )
        $price .= ' ' . __('per metre');

    return $price;
}

Код находится в файле function.php вашей активной дочерней темы (или активной темы).проверено и работает.

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...