With the following code I populate a select dropdown item in Admin product page which I add, through a function (in my theme's functions.php). For instance, I managed to get the list of all my product attributes (taxanomy):
<?php
$attributes = wc_get_attribute_taxonomies();
if($attributes) {
foreach ( $attributes as $attribute ) {
echo '<option value="'. $attribute->attribute_id .'">' . $attribute->attribute_label . '</option>';
}
}
?>
Any idea how the get the term names (labels) and ids of all the terms under a specific product attribute (taxanomy), for example pa_test?
You can use function get_terms() to get all the terms of our product attribute taxonomies as follows (here for product attribute pa_test taxonomy):
$taxonomy = 'pa_test';
$terms = get_terms( array('taxonomy' => $taxonomy, 'hide_empty' => false) );
// Loop through the terms for 'pa_test' taxonomy
foreach ( $terms as $term ) {
$term_name = $term->name; // name
$term_slug = $term->slug; // slug
$term_id = $term->term_id; // Id
$term_link = get_term_link( $term ); // Link
}
Related
I keep searching for a way to do this, but I can't find anything unfortunately.
I an trying to display all the product's attributes and values, separated by a pipe, in a custom place on the single-product (so for that I was thinking to create a shortcode, so I can place it anywhere I want). the output would be something like this:
BRAND: RENAULT | MODEL: 12 | YEAR: 1973
The code on the Woocommerce template product-attributes.php lists the attributes of the current product on single-product page, but it will list it with some styles I don't want in a place I don't want.
I want to create a shortcode with that code, which is:
<?php foreach ( $product_attributes as $product_attribute_key => $product_attribute ) : ?>
<?php echo wp_kses_post( $product_attribute['label'] ); ?>: <?php echo wp_kses_post( $product_attribute['value'] ); ?> |
<?php endforeach; ?>
How can I create a shortcode with it? I know the general code for a shortcode, but I don't know how to actually integrate the above one in it:
function custom_attributes_product_page() {
// integrate the required code
// Output needs to be return
return
}
// register shortcode
add_shortcode('custom-attributes', 'custom_attributes_product_page');
Would be great if this shortcode would list the attributes and their values separated by a column, like I said above (how to do that?)
Any help is highly appreciated.
Try the following shortcode that will display all product attribute(s) set for a product and their value(s), handling custom attributes too:
function get_product_attributes_shortcode($atts ) {
// Extract shortcode attributes
extract( shortcode_atts( array(
'id' => get_the_ID(),
), $atts, 'display-attributes' ) );
global $product;
if ( ! is_a($product, 'WC_Product') ) {
$product = wc_get_product( $id );
}
if ( is_a($product, 'WC_Product') ) {
$html = []; // Initializing
foreach ( $product->get_attributes() as $attribute => $values ) {
$attribute_name = wc_attribute_label($values->get_name());
$attribute_data = $values->get_data();
$is_taxonomy = $attribute_data['is_taxonomy'];
$option_values = array(); // Initializing
// For taxonomy product attribute values
if( $is_taxonomy ) {
$terms = $values->get_terms(); // Get attribute WP_Terms
// Loop through attribute WP_Term(s)
foreach ( $terms as $term ) {
$term_link = get_term_link( $term, $attribute );
$option_values[] = ''.$term->name.'';
}
}
// For "custom" product attributes values
else {
// Loop through attribute option values
foreach ( $values->get_options() as $term_name ) {
$option_values[] = $term_name;
}
}
$html[] = '<strong>' . $attribute_name . '</strong>: ' . implode(', ', $option_values);
}
return '<div class="product-attributes">' . implode(' | ', $html) . '<div>';
}
}
add_shortcode( 'display-attributes', 'get_product_attributes_shortcode' );
Code goes in functions.php file of the active child theme (or active theme). Tested and works.
USAGE: [display-attributes] or with a defined product Id [display-attributes id="254"]
You will get a display like: BRAND: RENAULT | MODEL: 12 | YEAR: 1973
If you don't want the linked terms, replace:
$term_link = get_term_link( $term, $attribute );
$option_values[] = ''.$term->name.'';
by this:
$option_values[] = $term->name;
I should get all the data of the products in the cart (product names and attributes of individual products). As a reference I have this code that allows to display only one attribute per product.
Could you help me to find the solution to see all attributes?
In the store there are 10 attributes in total
$taxonomy = 'pa_selezione-pezzi';
// 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;
// Output
$confirmation = str_ireplace("{term_slug}", $term_slug, $confirmation);
}
}
}
If you are looking to retrieve the product attributes set in product variation cart items, you can use the following code example:
// loop through product attributes
foreach( WC()->cart->get_cart() as $item ) {
if( ! empty($item['variation']) ) {
// loop through product attributes
foreach($item['variation'] as $attribute => $term_name ) {
$taxonomy = str_replace('attribute_', '', $attribute);
$attribute_name = wc_attribute_label($taxonomy);
$term_name = get_term_by( 'slug, $term_name, $taxonomy)->name;
}
}
}
Tested and works
Thank you for your correct answer "mr LoicTheAztec";
It has developed your codes, for the use of friends;
Note:attributes $value label added:
//اضافه کردن نام ویژگی به اسم محصول
//Add attribute label name to product name
if( $product->is_type( 'variation' ) ){
$s ='';
$s1 = '';
foreach ($product->get_attributes() as $taxonomy => $attribute_obj ) {
// Get the attribute label
$attribute_label_name = wc_attribute_label($taxonomy);
//convert to array
$attribute_arr = json_decode(json_encode($attribute_obj),true);
$term_name = get_term_by( 'slug', $attribute_arr, $taxonomy)->name;
$s = $s . $s1 .$attribute_label_name.':'.$term_name;
$s1 = ', ';
}
$name = $name . '(' .$s. ')';
echo '<p>' . $name. '</p>';
}
In WooCommerce I am using Category and Taxonomy Image plugin that allow me to add the images to product attribute terms.
Now I am trying to display for a specific product attribute, the related term images for each product on shop page.
The author of Category and Taxonomy Image plugin metion to use the following code to display a term image:
if (function_exists('get_wp_term_image'))
{
$meta_image = get_wp_term_image($term_id);
//It will give category/term image url
}
echo $meta_image; // category/term image url
I am using the code below to display "color" product attribute term names on the shop page:
add_action('woocommerce_after_shop_loop_item','add_attribute');
function add_attribute() {
global $product;
$spec_val = $product->get_attribute('spec');
if(!empty($spec_val)) {
echo'<span class="view_attr"> SPECIFICATION: ' . $spec_val . '</span>';
}
}
How To display the term images?
Maybe this is the solution:
add_action('woocommerce_after_shop_loop_item','woo_new_product_tab_content');
function woo_new_product_tab_content() {
global $product;
$ingredients = $product->get_attributes( 'color' );
foreach( $ingredients as $attr_name => $attr ){
foreach( $attr->get_terms() as $term ){
if ( wc_attribute_label( $attr_name ) == "Color" ) {
echo $term->name ;
$meta_image = get_wp_term_image($term->term_id);
echo '<img src="'.$meta_image.'"/>';
}
else echo '';
}
}
}
Product attributes is something very specific and more complex in WooCommerce than other taxonomies. Each product attribute is a taxonomy, has its own terms and can be used for variations on variable products...
The plugins Taxonomy Images and Category and Taxonomy Image allow to have images on all WooCommerce custom taxonomies terms as Product tag and Product attributes (product category has already this feature by default).
Here we use Category and Taxonomy Image and its dedicated function get_wp_term_image().
In the code below you can enable multiple product attributes defined in an array. if the option "Enable Archives?" is enable for the product attribute, you can optionally use the term links.
add_action('woocommerce_after_shop_loop_item','woo_new_product_tab_content');
function woo_new_product_tab_content() {
global $product;
// Define your product attribute labels in the array (label names)
$defined_pa_labels = array( 'Color' );
// Loop through WC_Product_Attribute Objects
foreach( $product->get_attributes() as $taxonomy => $product_attribute ) {
$taxonomy_name = $product_attribute->get_name(); // Slug
$taxonomy_label = wc_attribute_label( $taxonomy_name ); // Name (label name)
if( in_array( $taxonomy_label, $defined_pa_labels ) ) {
// Loop through product attribute WP_Term Objects
foreach( $product_attribute->get_terms() as $term ) {
$term_name = $term->name; // Term name
$term_slug = $term->slug; // Term slug
$term_id = $term->term_id; // Term ID
// Get product attribute term image
if( $image_url = get_wp_term_image( $term_id ) ) {
// Get product attribute term link (optional)
// if the product attribute is enabled on archives)
$term_url = get_term_link( $term, $taxonomy );
// Output
echo '<span style="text-align:center"><img src="'.esc_url( $image_url).'"/>'.$term->name.'</span>';
}
}
}
}
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
I create a sample 'woocommerce' product list, then the single product page has didn't get the attribute label of the product. below show the code
<?php if ( !$product->variations ) {return;}$field_name = isset($field_name) ? $field_name :'';$calendar_id = isset($calendar_id) ? $calendar_id : 0; <?php if ( $field_name ):?><?php foreach($product->variations as $variation_id => $variation_data):?><?php echo $variation_data['variation_title'];?><?php endforeach ?>
The variables $field_name and $calendar_id are not defined in your code, so I don't use them.
Your code seems to be outdated since Woocommerce 3. From a variable product object, to get the variation attributes label names / term names pairs, use the following:
<?php
if ( $product->is_type('variable') && $variations = $product->get_available_variations() ) {
$field_name = isset($field_name) ? $field_name : '';
$calendar_id = isset($calendar_id) ? $calendar_id : 0;
if ( sizeof( $variations ) > 0 ) {
// Loop through available product variations
foreach( $variations as $variation ) {
// Get variation title
$variation_title = get_the_title( $variation['variation_id'] );
// Display variation title
echo '<p><strong>Title:</strong> ' . $variation_title . '</p>';
// Loop through variation attributtes
foreach( $variation['attributes'] as $variation_attribute => $term_slug ){
// Get attribute taxonomy name
$taxonomy = str_replace( 'attribute_', '', $variation_attribute );
// Get attribute label name
$label_name = wc_attribute_label($taxonomy);
// Get attribute term name value
$term_name = ( $term = get_term_by( 'slug', $term_slug, $taxonomy ) ) ? $term->name : $term_slug;
// Display attribute label / term name pairs
echo '<p><strong>' . $label_name . ':</strong> ' . $term_name . '</p>';
}
}
}
}
?>
Tested and works in Woocommerce 3+
I've found various snippets online to list the woocommerce product categories, but I can't find a snippet that lists the subcategories and sub-sub categories for a given category.
How can I get the subcategories of a given product category?
This is possible with a custom function in which you will set your "parent" product category slug:
function get_product_subcategories_list( $category_slug ){
$terms_html = array();
$taxonomy = 'product_cat';
// Get the product category (parent) WP_Term object
$parent = get_term_by( 'slug', $category_slug, $taxonomy );
// Get an array of the subcategories IDs (children IDs)
$children_ids = get_term_children( $parent->term_id, $taxonomy );
// Loop through each children IDs
foreach($children_ids as $children_id){
$term = get_term( $children_id, $taxonomy ); // WP_Term object
$term_link = get_term_link( $term, $taxonomy ); // The term link
if ( is_wp_error( $term_link ) ) $term_link = '';
// Set in an array the html formated subcategory name/link
$terms_html[] = '' . $term->name . '';
}
return '<span class="subcategories-' . $category_slug . '">' . implode( ', ', $terms_html ) . '</span>';
}
Code goes in function.php file of your active child theme (or active theme).
Tested and works.
Usage example:
echo get_product_subcategories_list( 'clothing' );
You will get an horizontal coma separated list (with links) of all subcategories for this given category
This is the code for get subcategory of given category:
$categories = get_the_terms( get_the_ID(), 'product_cat' );
//For checking category exit or not
if ( $categories && ! is_wp_error( $category ) ) :
foreach($categories as $category) :
// get the children (if any) of the current cat
$children = get_categories( array ('taxonomy' => 'product_cat', 'parent' => $category->term_id ));
if ( count($children) == 0 ) {
// if no children, then echo the category name.
echo $category->name;
}
endforeach;
endif;