Reputation: 75
I would like to display the current category in the product name in woocommerce. What only applies for variable products.
The code below is partly working, but need some reforming:
1 - to be applied for only for variable products.
2 - to show the current category that the viewer is in not the main product category.
remove_action('woocommerce_shop_loop_item_title', 'woocommerce_template_loop_product_title', 10);
function loop_title() {
global $post;?>
<div class="col-xl-3 col-md-3 col-sm-3">
<h2><a href="<?php the_permalink(); ?>" class="feed-item-baslik"><?php the_title(); ?> <?php
$terms = get_the_terms( $post->ID, 'product_cat' );
if ( $terms && ! is_wp_error( $terms ) ) :
if ( ! empty( $terms ) ) {
echo $terms[0]->name;
}?>
<?php endif;?></a></h2>
</div>
<?php }
add_action('woocommerce_shop_loop_item_title', 'loop_title', 10);
Upvotes: 2
Views: 2148
Reputation: 253784
Updated: The following should work as you are expecting:
add_action( 'woocommerce_shop_loop_item_title', 'custom_shop_loop_item_title', 5 );
function custom_shop_loop_item_title() {
global $product;
if ( $product->is_type('variable') && is_product_category() ) {
remove_action('woocommerce_shop_loop_item_title', 'woocommerce_template_loop_product_title', 10);
add_action('woocommerce_shop_loop_item_title', 'custom_product_loop_title', 10);
}
}
function custom_product_loop_title() {
$taxonomy = 'product_cat';
$queried_object = get_queried_object();
?>
<div class="col-xl-3 col-md-3 col-sm-3">
<h2><a href="<?php the_permalink(); ?>" class="feed-item-baslik"><?php the_title();
// For product category archives pages
if( is_a($queried_object, 'WP_Term') && $queried_object->taxonomy === $taxonomy ) {
echo ' ' . $queried_object->name;
}
?></a></h2>
</div>
<?php
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
Upvotes: 3