How to add Brands to WooCommerce products
In this article, we’ll show you how to add a custom taxonomy called “Brands” to your WooCommerce products. We’ll also show you how to add an image field to this taxonomy and how to create a shortcode to display these images with links to the products filtered by each brand.
Create the “Brands” Taxonomy
First, we need to register the new taxonomy “Brands.” To do this, add the following code to your theme’s functions.phpfile:
_x('Brands', 'taxonomy general name', 'textdomain'),
'singular_name' => _x('Brand', 'taxonomy singular name', 'textdomain'),
'search_items' => __('Search Brands', 'textdomain'),
'all_items' => __('All Brands', 'textdomain'),
'parent_item' => __('Parent Brand', 'textdomain'),
'parent_item_colon' => __('Parent Brand:', 'textdomain'),
'edit_item' => __('Edit Brand', 'textdomain'),
'update_item' => __('Update Brand', 'textdomain'),
'add_new_item' => __('Add New Brand', 'textdomain'),
'new_item_name' => __('New Brand Name', 'textdomain'),
'menu_name' => __('Brands', 'textdomain'),
);
$args = array(
'hierarchical' => true,
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => array('slug' => 'brand'),
);
register_taxonomy('brand', array('product'), $args);
}
add_action('init', 'create_brand_taxonomy', 0);
This code creates a new hierarchical taxonomy called “Brands” that can be used to categorize products.
Add an image field to the “Brands” taxonomy
To add an image field to our “Brands” taxonomy, we can use the following code:
term_id, 'brand_image', true);
?>
This code adds an image field to the creation and editing form of the “Brands” taxonomy, allowing you to upload and save images.
Create a shortcode to list Brand images
Finally, we create a shortcode to display the brand images with links to the products filtered by each brand:
'brand',
'hide_empty' => false,
));
if (!empty($terms) && !is_wp_error($terms)) {
$output = '';
foreach ($terms as $term) {
$image = get_term_meta($term->term_id, 'brand_image', true);
$term_link = get_term_link($term);
if ($image) {
$output .= '';
$output .= '';
$output .= '
';
$output .= '';
$output .= '';
}
}
$output .= '';
} else {
$output = __('No brands available.', 'textdomain');
}
return $output;
}
add_shortcode('brand_images', 'brand_images_shortcode');
This shortcode [brand_images] can be used on any page or post to display the brand images with links to the products filtered by each brand.
By following these steps, you’ve successfully added a custom “Brands” taxonomy to your WooCommerce products, including an image field for each brand, and created a shortcode to display these images. This will help you better organize your products and offer a more personalized shopping experience for your customers.
We hope this tutorial was helpful! If you have any questions, feel free to leave a comment.
