问题
I have a Wordpress (version 4.2.2) eCommerce site running WooCommerce (version 2.3.8).
On my individual product page I wish to set the title of the product to also include the custom categories I have created in WooCommerce and that this product belongs to.
I find the following file (wp-content/themes/mytheme/woocommerce/single-product/title.php) that relates to the title of the individual product and edit it as below to try and include the categories that this product belongs to in the title as well.
With the code below I manage to display the categories, but the problem is that I am displaying ALL categories, and not just the categories that this product belongs to.
How do I limit the categories returned to only the categories that the product belongs to please?
<?php
if ( ! defined( 'ABSPATH' ) )
exit; // Exit if accessed directly
?>
<!-- Original Product Title START -->
<h1 itemprop="name" class="product-title entry-title">
<?php the_title(); ?>
</h1>
<!-- Original Product Title END -->
<!-- New Product Title START -->
<h1 itemprop="name" class="product-title entry-title">
<?php
$taxonomy = 'product_cat';
$orderby = 'name';
$show_count = 0; // 1 for yes, 0 for no
$pad_counts = 0; // 1 for yes, 0 for no
$hierarchical = 1; // 1 for yes, 0 for no
$title = '';
$empty = 0;
$args = array(
'taxonomy' => $taxonomy,
'orderby' => $orderby,
'show_count' => $show_count,
'pad_counts' => $pad_counts,
'hierarchical' => $hierarchical,
'title_li' => $title,
'hide_empty' => $empty
);
?>
<?php
$all_categories = get_categories( $args );
foreach ($all_categories as $cat)
{
if($cat->category_parent == 0)
{
$category_id = $cat->term_id;
?>
<?php
echo '<br /><a href="'. get_term_link($cat->slug, 'product_cat') .'">'. $cat->name .'</a>';
?>
<?php
$args2 = array(
'taxonomy' => $taxonomy,
'child_of' => 0,
'parent' => $category_id,
'orderby' => $orderby,
'show_count' => $show_count,
'pad_counts' => $pad_counts,
'hierarchical' => $hierarchical,
'title_li' => $title,
'hide_empty' => $empty
);
$sub_cats = get_categories( $args2 );
if($sub_cats)
{
foreach($sub_cats as $sub_category)
{
echo '<br/><a href="'. get_term_link($sub_category->slug, 'product_cat') .'">'. $sub_category->name .'</a>';
echo apply_filters( 'woocommerce_subcategory_count_html', ' <span class="cat-count">' . $sub_category->count . '</span>', $category );
}
}
?>
<?php
}
}
?>
</h1>
<!-- New Product Title END -->
回答1:
you can simply get all the categories assign to product by using get_the_terms
$terms = get_the_terms( get_the_ID(), 'product_cat' );
foreach ($terms as $term) {
echo '<h1 itemprop="name" class="product-title entry-title">'.$term->name.'</h1>';
}
回答2:
Use the get_categories function to retrieve categories name :-
You can use this code to display product categories name -
<?php global $post, $product;
$categ = $product->get_categories();
echo $categ; ?>
来源:https://stackoverflow.com/questions/30592156/woocommerce-display-product-categories-in-product-title