问题
I am accessing archive-products.php
on woocommerce to display my products (like the normal process in woocommerce).
On the page of archive-products.php I have added the sidebar with all the product categories that my shop has (with or without products). I have used the following code to do so:
$taxonomy = 'product_cat';
$orderby = 'ID';
$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 = '<h2>' . _x('Our Products', 'mfarma') . '</h2>';
$hide_empty = 0;
$args = array(
'taxonomy' => $taxonomy,
'orderby' => $orderby,
'order' => 'ASC',
'show_count' => $show_count,
'pad_counts' => $pad_counts,
'hierarchical' => $hierarchical,
'title_li' => $title,
'hide_empty' => $hide_empty
);
?>
<ul>
<?php wp_list_categories($args); ?>
</ul>
Now the left side of the page has the above sidebar and the right one has the products. In each product category I have added a small description with an html format that I want to show when the user has clicked the category. According to woocommerce when you go to a specific category (in my case, http://localhost/product-category/mycategory
) it is still the archive-products.php.
I am trying to get the term_id from the link clicked, but the loop (and the global $post) points me to the first product of the list instead of the category that I need. So if a category has zero products, I can't get the term ID
. How do I get that term ID from archive-products.php?
回答1:
Found the answer for something else but it also applies to my question.
add_action('woocommerce_archive_description', 'woocommerce_category_description', 2);
function woocommerce_category_description() {
if (is_product_category()) {
global $wp_query;
$cat = $wp_query->get_queried_object();
echo "CAT IS:".print_r($cat,true); // the category needed.
}
}
回答2:
You can do it simplier:
Print current category:
single_cat_title(); // this prints your current category
Get current category string:
single_cat_title('', false); // this returns your current category
echo single_cat_title('', false); // for print current category
来源:https://stackoverflow.com/questions/24138701/woocommerce-how-to-get-current-category