Get the Description of Product Variations Attributes terms - php

In Woocommerce I have these attributes and the terms for them:
color: blue(description=1), red(description=2)
size: xl(description=10), m(description=20)
All terms have description fields mentioned above.
For a variable product, I have these variations:
blue-m
red-xl
For the purpose of auto-generating the variations SKU (based on those descriptions) I need to get the description for the attribute term used in each variant (we use different attributes for each variable product).
For example for the variation with red color and xl size, I want to get something like 210 (from descriptions of red and xl)
I tried using $variation['attributes'] and removing extra characters from it to use with get_terms to get the descriptions of the attributes used in a variant, but I couldn't succeed.
Any Idea?

This can be done in an easily once you get the Product variation ID $variation_id this way:
// Initializing
$variation_sku = '';
// Get the product variation object (instance)
$variation = wc_get_product( $variation_id );
// Loop through variation attributes "taxonomy" / "terms" pairs
foreach( $variation->get_variation_attributes() as $attribute => $value ){
$taxonomy = str_replace( 'attribute_', '', $attribute );
$term = get_term_by( 'slug', $value, $taxonomy );
// $term_name = $term->name;
$variation_sku .= $term->description; // <= HERE the Description
}
// Displaying the sku
echo '<p>'.__("SKU: ").$variation_sku.'</p>';

Related

Exclude products with specific attributes terms from WooCommerce coupons

I would like to exclude from all WooCommerce coupons the products that have a specific attribute (e.g. attribute_pa_brand => mybrand).
I followed this answer Exclude variations with 2 specific attribute terms from coupon usage in Woocommerce but it seems to apply only to the Variable Product type, while I would only need it for the Simple Product.
I will be grateful for any answer.
The linked code from your question is for product variation type. Now to make it work for simple products and variable products (without targeting specific variations attributes terms), you will use the following:
add_filter( 'woocommerce_coupon_is_valid', 'custom_coupon_validity', 10, 3 );
function custom_coupon_validity( $is_valid, $coupon, $discount ){
// YOUR ATTRIBUTE SETTINGS BELOW:
$taxonomy = 'pa_brand'; // Set the taxonomy (start always with "pa_" + the slug)
$term_names = array('Apple', 'Sony'); // Set your term NAMES to be excluded
$term_ids = array(); // Initializing
// Convert term names to term Ids
foreach ( $term_names as $term_name ) {
// Set each term id in the array
$term_ids[] = get_term_by( 'name', $term_name, $taxonomy )->term_id;
}
// Loop through cart items and check for backordered items
foreach ( WC()->cart->get_cart() as $cart_item ) {
$product = $cart_item['variation_id'] > 0 ? wc_get_product($cart_item['product_id']) : $cart_item['data'];
// Loop through product attributes
foreach( $product->get_attributes() as $attribute => $values ) {
if( $attribute === $taxonomy && array_intersect( $values->get_options(), $term_ids ) ) {
$is_valid = false; // attribute found, coupons are not valid
break; // Stop and exit from the loop
}
}
}
return $is_valid;
}
Code goes in functions.php file of the active child theme (or active theme). Tested and works for simple and variable products on last WooCommerce version.

Get the category name from a WooCommerce product using the product id or the category id

I am trying to get the category name of a product (for example "nutrition", "sport", etc), but I can't.
I'm trying this way:
$test = wc_get_product_category_list(1202);
But what I get is the following:
Batidos,
Nutrición
I just need the tag "Batidos", "Nutrición"...
I would really appreciate any help, I've been trying and reading for a long time but I can't ...
Regards and thanks.
To get the product category name(s) from a product Id, use instead wp_get_post_terms() function:
$product_id = 1202; // product Id
$term_names_array = wp_get_post_terms( $product_id, 'product_cat', array('fields' => 'names') ); // Array of product category term names
$term_names_string = count($term_names_array) > 0 ? implode(', ', $term_names_array) : ''; // Convert to a coma separated string
echo $term_names_string; // Display the string
To get the product category name from a product category Id, use get_term-by() function as follows:
$term_id = 125; // Product category term Id
$term = get_term-by( 'term_id', $category_term_id, 'product_cat' ); // The WP_Term Object
$term_name = $term->name; // Get the term name from the WP_Term Object
echo $term_name; // Display
Tested and works.

Show WooCommerce product tag name set for a product with a shortcode

As the title says I’m looking for a shortcode I can use to show the tag of a specific product. All my products have only one product tag set for each.
For example, if the product with ID: 1250 has the tag “Horse” I need the way to put a shortcode specifying the ID of the product and show your respective tag. In the example the shortcode should show on the screen the word “Horse”
Tyring to modify the following code to achieve it:
$terms = wp_get_post_terms( get_the_id(), 'product_tag' );
if( count($terms) > 0 ){
foreach($terms as $term){
$term_id = $term->term_id; // Product tag Id
$term_name = $term->name; // Product tag Name
$term_slug = $term->slug; // Product tag slug
$term_link = get_term_link( $term, 'product_tag' );
$output[] = '.$term_name.';
}
$output = implode( ', ', $output );
echo $output;
}
But I don't have the enough knowledge to achieve it
Any help is appreciated.
If you have only one product tag set for each product, the following shortcode function will output the product tag term name set for the current product (or a string of coma separated term names, when there are multiple terms set for a product). It works also for a defined product Id as argument in the shortcode (see usage examples).
The function code:
add_shortcode( 'wc_product_tag', 'get_tag_term_name_for_product_id' );
function get_tag_term_name_for_product_id( $atts ) {
// Shortcode attribute (or argument)
extract( shortcode_atts( array(
'taxonomy' => 'product_tag', // The WooCommerce "product tag" taxonomy (as default)
'product_id' => get_the_id(), // The current product Id (as default)
), $atts, 'wc_product_tag' ) );
$term_names = (array) wp_get_post_terms( $product_id, $taxonomy, array('fields' => 'names') );
if( ! empty($term_names) ){
// return a term name or multiple term names (in a coma separated string)
return implode(', ', $term_names);
}
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
USAGE examples:
For the current product: [wc_product_tag]
or in php: echo do_shortcode('[wc_product_tag]');
For a defined product id: [wc_product_tag product_id="37"]
or in php: echo do_shortcode('[wc_product_tag product_id="37"]');
This also works for any product custom taxonomy, as WooCommerce product category…
To display WooCommerce product category term names set for a product you need to replace:
'taxonomy' => 'product_tag', // The WooCommerce "Product Tag" taxonomy (as default)
by the following line:
'taxonomy' => 'product_cat', // The WooCommerce "Product Category" taxonomy (as default)

Woocommerce -- Get Attribute Value For Products in Cart

I am using Woocommerce to set up an ecommerce page that sells meal plans.
Currently, I have a product customizer that allows the customer to create their own meal plan / composite.
I am trying to pass some values on to the plugin's widget. Specifically, I am attempting to retrieve the names and values of product attributes that are currently in my cart.
The product attributes display nutrition information for each composite product. When a customer adds a product to their cart, I would like the nutrition info (product attributes) to populate.
For the first piece, I was able to retrieve product attribute names for in-cart items by using the below code (from here):
$item_data = $cart_item['data'];
// print_r($item_data);
$attributes = $item_data->get_attributes();
//print_r($attributes);
foreach ( $attributes as $attribute => $attribute_term ) {
$term = get_term_by('slug', $attribute_name, $attribute);
echo wc_attribute_label( $attribute ).': '.$term->term;
}
This only displays the name of the attribute. Exactly what I need for column 1.
However, I want to display the attribute value in column 2, but I'm unsure how to manipulate the above code to achieve this. Currently, I have the same code passed into column 2
Example of current situation
So step 1 (above), would be to print the product attribute values that correspond to the product attribute name in column 1.
Step 2 would be to take this a little further by summing up attributes that are common between products. For instance, if product 1 and product 2 both have the "fats" attribute with values of "2" and "3" accordingly, then I hope to print out "5" (the sum for the common product attributes).
Any insight is greatly appreciated. I have limited programming knowledge, and am learning as I go with this project.
Here is example code that might help you
add_filter( 'woocommerce_cart_item_name', 'customizing_cart_item_data', 10, 3);
function customizing_cart_item_data( $item_name, $cart_item, $cart_item_key ) {
$term_names = array();
// Get product categories
$terms = wp_get_post_terms( $cart_item['product_id'], 'product_cat' );
if( count($terms) > 0 ){
foreach( $terms as $term ) $term_names[] = $term->name;
$item_name .= '<p class="item-category" style="margin:12px 0 0; font-size: .875em;">
<strong class="label">' . _n( 'Category', 'Categories', count($terms), 'woocommerce' ) . ': </strong>
<span class="values">' . implode( ', ', $term_names ) . '</span>
</p>';
}
return $item_name;
}

Get a specific attribute taxonomy terms slug

I'm trying to get terms slug from a specific attribute taxonomy but I get nothing.
$attr_langs = 'pa_languages';
$attr_langs_meta = get_post_meta('id', 'attribute_'.$attr_langs, true);
$term = get_term_by('slug', $attr_langs_meta, $attr_langs);
Thank you so much in advance!
It's normal that it doesn't work as get_post_meta() first function argument needs to be a numerical value but NOT a text string as 'id' (the post ID)…
So you can't get any value for $attr_langs_meta variable.
You can get the product ID in different ways:
1) From the WP_Post object with:
global $post;
$product_id = $post->ID;
2) From the WC_Product object with:
$product_id = $product->get_id();
Now the correct way for to do it is:
// The defined product attribute taxonomy
$taxonomy = 'pa_languages';
// Get an instance of the WC_Product Object (necessary if you don't have it)
// from a dynamic $product_id (or defined $product_id)
$product = wc_get_product($product_id);
// Iterating through the product attributes
foreach($product->get_attributes( ) as $attribute){
// Targeting the defined attribute
if( $attribute->get_name() == $taxonomy){
// Iterating through term IDs for this attribute (set for this product)
foreach($attribute->get_options() as $term_id){
// Get the term slug
$term_slug = get_term( $term_id, $taxonomy )->slug;
// Testing an output
echo 'Term Slug: '. $term_slug .'<br>';
}
}
}
Or also exclusively for a variable product (similar thing):
// The defined product attribute taxonomy
$taxonomy = 'pa_languages';
// Get an instance of the WC_Product Object (necessary if you don't have it)
// from a dynamic $product_id (or defined $product_id)
$product = wc_get_product($product_id);
// Iterating through the variable product variations attributes
foreach ( $product->get_variation_attributes() as $attribute => $terms ) {
// Targeting the defined attribute
if( $attribute == $taxonomy ){
// Iterating through term slugs for this attribute (set for this product)
foreach( $terms as $term_slug ){
// Testing an output
echo 'Term Slug: ' . $term_slug . '<br>';
}
}
}
This should work for you…

Categories