Добавить текст перед ценой продукта для определенной категории в Woocommerce - PullRequest
2 голосов
/ 29 марта 2019

В woocommerce я использую " Добавить текст перед ценой продукта, если он превышает определенную сумму в Woocommerce " код ответа, который добавляет текст перед всеми ценами.

Как я могу заставить этот код работать только для определенной категории продуктов?

Любая помощь приветствуется.

Ответы [ 2 ]

1 голос
/ 29 марта 2019

Следующий код будет работать для определенной категории продуктов. Код обрабатывает родительские категории продуктов и варианты продуктов, используя пользовательскую условную функцию для категорий продуктов:

// Custom conditional function that handle parent product categories too
function has_product_categories( $product_id, $categories ) {
     // 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', 'prepend_text_to_product_price', 20, 2 );
function prepend_text_to_product_price( $price_html, $product ) {
    // HERE set your product category in the array
    $product_category = array('clothing');

    // Only on frontend and excluding min/max prices for variable products
    if( is_admin() || $product->is_type('variable') )
        return $price_html;

    // Get the variable product ID for product variations (as variations dont handle product categories)
    $product_id = $product->is_type('variation') ? $product->get_parent_id() : $product->get_id();

    // Only for a specific product category
    if( ! has_product_categories( $product_id, $product_category ) )
        return $price_html;

    // Get product price
    $price = (float) $product->get_price(); // Regular price

    if( $price > 15 )
        $price_html = '<span>'.__('(GRATIS)', 'woocommerce' ).'</span> '.$price_html;

    return $price_html;
}

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


Вы также можете использовать has_term() условную функцию (без обработки родительских категорий продуктов) :

add_filter( 'woocommerce_get_price_html', 'prepend_text_to_product_price', 20, 2 );
function prepend_text_to_product_price( $price_html, $product ) {
    // HERE set your product category in the array
    $product_category = array('clothing');

    // Only on frontend and excluding min/max prices for variable products
    if( is_admin() || $product->is_type('variable') )
        return $price_html;

    // Get the variable product ID for product variations (as variations dont handle product categories)
    $product_id = $product->is_type('variation') ? $product->get_parent_id() : $product->get_id();

    // Only for a specific product category
    if( ! has_product_categories( $product_id, $product_category ) )
        return $price_html;

    // Get product price
    $price = (float) $product->get_price(); // Regular price

    if( $price > 15 )
        $price_html = '<span>'.__('(GRATIS)', 'woocommerce' ).'</span> '.$price_html;

    return $price_html;
}

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

Тема по теме: Добавить текст перед ценой товара, если она выше определенной суммы в Woocommerce

0 голосов
/ 29 марта 2019

Это должно работать: добавлен has_term для категории к существующему ответу на этот вопрос.

if ( has_term( 'putcategorynamehere', `'product_cat'` ) ) {
add_filter( 'woocommerce_get_price_html', 'prepend_text_to_product_price', 20, 2 );
function prepend_text_to_product_price( $price_html, $product ) {
    // Only on frontend and excluding min/max prices on variable products
    if( is_admin() || $product->is_type('variable') ) 
        return $price_html;

    // Get product price
    $price = (float) $product->get_price(); // Regular price

    if( $price > 15 )
        $price_html = '<span>'.__('(GRATIS)', 'woocommerce' ).'</span> '.$price_html;

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