I am looking for a function to convert the woocommerce category id into a category slug for a breadcrumb link.
The following loop pulls the upper most product category ID for product pages. This is necessary because some of my products have 4 or 5 levels of hierarchy.
This is working fine.
$prod_terms = get_the_terms( $post->ID, 'product_cat' );
foreach ($prod_terms as $prod_term) {
// gets product cat id
$product_cat_id = $prod_term->term_id;
// gets an array of all parent category levels
$product_parent_categories_all_hierachy = get_ancestors( $product_cat_id, 'product_cat' );
// This cuts the array and extracts the last set in the array
$last_parent_cat = array_slice($product_parent_categories_all_hierachy, -1, 1, true);
foreach($last_parent_cat as $last_parent_cat_value){
}
}
At this point echo $last_parent_cat_value; would give you the ID of the highest category.
In order to turn this into a breadcrumb link I need to pull the category name. so...
// This function turns Category Ids produced by the foreach loop above into Names
function woocommerceCategoryName($id){
$term = get_term( $id, 'product_cat' );
return $term->name;
}
Now all I need is the slug to complete the link. so...
//this function gets the category slug from the category id
function get_cat_slug($cat_id) {
$cat_id = (int) $cat_id;
$category = &get_category($cat_id);
return $category->slug;
}
but when I echo
echo '' . woocommerceCategoryName($last_parent_cat_value) . '';
My Name function is working but my slug function is not.
Can anyone shine any light into my error?
when I inspect element on the front end here is my generated html...
Sports
Could I try and use the Name to generate the slug?
Thanks for reading.
okay, I am not sure why the above wasn't working, or why the following worked.
//I copied the function to generate the name, and generated a slug instead...
function woocommerceCategorySlug($id){
$term = get_term( $id, 'product_cat' );
return $term->slug;
}
echo '' . woocommerceCategoryName($last_parent_cat_value) . '';
Thanks again for reading, I hope this can help someone else.
Related
I'm trying to display an image in a custom field on child category archive pages.
The current setup is:
<?php
$term_id = get_queried_object()->term_id;
$post_id = 'product_cat_'.$term_id;
$custom_field = get_field('brand_background', $post_id);
?>
<div id="brandHeader" class="brand-header-logo" style="background-image: url('<?php the_field('brand_background', $post_id); ?>');">
This obviously gets the 'background image' field from the category archive it's currently on.
If the category is a child category I want to be able to pull the 'background image' from the parent category. I've tried a few things but doesn't seem to be working - can anyone help?
You could use the get_ancestors function to get the parent id and use that id to get your field:
get_ancestors
So let's say your categories looks like this:
-Parent (id = 24)
--Child (id = 42)
$term_id = get_queried_object()->term_id;
$term_ancestor_ids = get_ancestors($term_id, 'product_cat');
// if you do a print_r on $term_ancestor_ids
// you'll see this:
// Array ( [0] => 24 )
$post_id = 'product_cat_'.$term_ancestor_ids[0];
$custom_field = get_field('brand_background', $post_id);
Tested and works, let me know if you were able to get it to work too!
I'm making my first theme and everything is progressing real fast thanks to all the assistance offered by The Loop and WooCommerce's SDK. Then today I spent an entire day failing to do something as simple as showing an image... After an entire day of struggling the only things I managed to learn is that WP seems to offer NO means for fetching a category's image and MANY people have asked this question for many years and STILL I can't find a way to ACTUALLY do it...
:(
What I want to do is create a slider above my store that shows the images of a curated selection of shop categories. I want to be able to enter a list of term names and based on that my function should generate links to the product categories in the form of the category's image.
Sounds simple... turns out, it's nowhere near CLOSE to simple... Before you go off and mark this as a duplicate question, let me explain why I am asking it...
Some of the solutions I have found require that I know the term's IDs, not the tern name. Some say "Get the id's using a custom term search" but doesn't explain how. I know how to do custom taxonumy based queries for posts but not for terms. the documentation confuses me in terms of what values to pass to query terms :(
Other solutions require that I first find a product of a specific category and then find the product's category image working backwards from there (????)
Then of course there is the default answer people love to give for everything: "Oh you are designing your own theme and want to show category icons? Simple, just download a plugin to do that for you". Now why didn't I think of just including someone else's plugin into my theme? (facepalm)
Other answers just show how to print the list of term names but nothing so far has been able to let me do what should have been been as simple as this:
$categories = array("software", "plugins", "merch");
foreach($categories as $cat) {
$term_id = get_term_id($cat);
$term_image = get_term_featured_image($term_id);
echo '<img src="'.$term_image.'">;
}
First problem with getting the term is that the wordpress function to get the term id only works on the category taxonomy but I need to query WooCommerce's product_cat taxonomy. Secondly there doesn't seem to be an option to fetch the thumbnail/featured image even if you HAVE an id. So now what?
So I went low level and started querying the tables directly using $wpdb and I determine the term I am after has term_id 94. I query the termmeta table for the thumbnail's post ID and I find it is 905. Now I turn to my posts table and find.... there IS no post entry 905! WTF? So I do this for two more categories and find the same thing. Finding the image's id results in nothing being returned from the attempt at extracting the post's attachments since there IS no post matching the image's id...
Why is this so darned hard? WordPress makes everything else so incredibly simple yet this simple sounding task seems to be near impossible to do... so now that you see I have Googled this to death and struggled my backside off already, I am asking this question out of desperation:
How do I take an array of product_cat term names and convert that into an array of url's to display the category's image?
Thanks
The shortest way is to use woocommerce_subcategory_thumbnail() dedicated function:
$product_categories = array("software", "plugins", "merch");
// Loop through the product categories
foreach( $product_categories as $category ) {
// Get the WP_term object
$term = get_term_by( 'slug', sanitize_title( $category ), 'product_cat' );
// Get the term link (if needed)
$term_link = get_term_link( $term, 'product_cat' );
// Display the product category thumbnail
woocommerce_subcategory_thumbnail( $term );
}
The other step by step way, that will display the linked product category image with its name:
$product_categories = array("software", "plugins", "merch");
// Loop through the product categories
foreach( $product_categories as $category ) {
// Get the WP_term object
$term = get_term_by( 'slug', sanitize_title( $category ), 'product_cat' );
// Get the term link (if needed)
$term_link = get_term_link( $term, 'product_cat' );
// Get the thumbnail Id
$thumbnail_id = (int) get_woocommerce_term_meta( $term->term_id, 'thumbnail_id', true );
if( $thumbnail_id > 0 ) {
// Get the attchement image Url
$term_img = wp_get_attachment_url( $thumbnail_id );
// Formatted thumbnail html
$img_html = '<img src="' . $term_img . '">';
} else {
$img_html = '';
}
echo '' . $img_html . $term->name . '<br>';
}
Both works…
To get all product categories WP_Term objects and display them with their thumbnails:
// Get all product categories
$product_category_terms = get_terms( array(
'taxonomy' => "product_cat",
'hide_empty' => 1,
));
foreach($product_category_terms as $term){
// Get the term link (if needed)
$term_link = get_term_link( $term, 'product_cat' );
## -- Output Example -- ##
// The link (start)
echo '<a href="' . $term_link . '" style="display:inline-block; text-align:center; margin-bottom: 14px;">';
// Display the product category thumbnail
woocommerce_subcategory_thumbnail( $term );
// Display the term name
echo $term->name;
// Link close
echo '</a>';
}
For example :
- A = 21
- B = 22
- C = 23
How can I get 21 and 22 IDs using 23 sub Id?
Updated (2020)
To get the parent terms Ids from a product category term ID, try the following (code is commented):
// Get the parent term slugs list
$parent_terms_list = get_term_parents_list( 23, 'product_cat', array('format' => 'slug', 'separator' => ',', 'link' => false, 'inclusive' => false) );
$parent_terms_ids = []; // Initialising variable
// Loop through parent terms slugs array to convert them in term IDs array
foreach( explode(',', $parent_terms_list) as $term_slug ){
if( ! empty($term_slug) ){
// Get the term ID from the term slug and add it to the array of parent terms Ids
$parent_terms_ids[] = get_term_by( 'slug', $term_slug, 'product_cat' )->term_id;
}
}
// Test output of the raw array (just for testing)
print_r($parent_terms_ids);
Tested and works.
Addition:
You can better use Wordpress get_ancestors() dedicated function, like in this recent answer thread or on those other related answers.
In this case the code is going to be:
// Get the parent term ids array
$parent_terms_ids = $parent_ids = get_ancestors( $child_id, 'product_cat' , 'taxonomy');
// Test output of the raw array (just for testing)
print_r($parent_terms_ids);
Related treads:
woocommerce - How do I get the most top level category of the current product category
Get top level parent product category as body class in WooCommerce
List product categories hierarchy from a product id in Woocommerce
Related documented Wordpress functions:
Documented Wordpress function get_term_parents_list()
Documented Wordpress function get_term_by()
Documented Wordpress function get_ancestors()
function parentIDs($sub_category_id)
{
static $parent_ids = [];
if ( $sub_category_id != 0 ) {
$category_parent = get_term( $sub_category_id, 'product_cat' );
$parent_ids[] = $category_parent->term_id;
parentIDs($category_parent->parent);
}
return $parent_ids;
}
$sub_category_id = 23;
$parent_ids_array = parentIDs($sub_category_id);
echo "<pre>";
print_r($parent_ids_array);
echo "</pre>";
The fastest way to get the parents ids is to use the built in function given and documented by Wordpress. See get_ancestors
if you have checked get_term_parents_list you will see that it uses get_ancestors see this link
https://core.trac.wordpress.org/browser/tags/5.4/src/wp-includes/category-template.php#L1362
So the short answer is just below code.
$parent_ids = get_ancestors( $child_id, 'product_cat' , 'taxonomy');
If you look at the documentation for get_category_parents()
you'll see that it resturns a string where the names of the categories are seperated by a seperator. Now, I don't know if this is just me but this seems extremely stupid. What I'm expecting is an array of actual category objects. Can't have everything I guess..
What would be the best way to get the parent categories in the format that I want them?
Try something like this:
$categories = [];
$parents = get_category_parents( $cat, false, ',' );
foreach($parents as $parent){
$categories[] = get_term_by('name', $parent, 'category');
}
Not tested.
Try this one you will get correct result
if your want to get parent category of a post then try this
$parent_cat_array = get_post_ancestors( $post ); //$post is an object or you can pass post id also
if you want get parent with category id then try this one...
// determine the topmost parent of a term
function get_term_top_most_parent($term_id, $taxonomy) {
// start from the current term
$parent = get_term_by('id', $term_id, $taxonomy);
// climb up the hierarchy until we reach a term with parent = '0'
while ($parent->parent != '0') {
$term_id = $parent->parent;
$parent = get_term_by('id', $term_id, $taxonomy);
}
return $parent;
}
function to place in functions.php
call this function in your page, post or custom template
$term_parent = get_term_top_most_parent($term_id, $taxonomy);
// in case of default category then your taxonomy is category
Here is the function that return you most parent category or custom taxonomy
Tested!!!
I have a wp template that I would like to assign to some pages. The template would ie. display all WooCommerce products that have the same master category name as the pages name itself.
By far I have tried using this code, but with no good output:
$idObj = get_category_by_slug($pagename);
$id = $idObj->term_id;
echo ": ". $id;
Unfortunately, the echo does not display anything.
Echoing $pagename works, and returns me the slug of the page.
Any good way I could make this work?
With a custom taxonomy is recommended to use get_term_by() instead :
$category = get_term_by( 'slug', $pagename, 'product_cat' );
$cat_id = $category->term_id
Reference: Get category ID from term slug…
To get a product category ID from term name, use:
$category = get_term_by( 'name', $pagename, 'product_cat' );
$cat_id = $category->term_id
The code seems to be correct, try a var_dump to see what you are getting from get_category_by_slug($pagename)
$idObj = get_category_by_slug($pagename);
var_dump($idObj);