How can I get the parent category from a sub category page in WooCommerce? After doing extensive research this piece of code looks promising
get_ancestors( $product_cat_id, 'product_cat' );
but it keeps returning 'array' in a loop.
$parentcats = get_ancestors($product_cat_id, 'product_cat');
This is the correct way and you will get one or more parent categories, as an array and loop over it to get the value like below:
foreach($parentcats as $parentcat){
echo $parentcat;
}
Related
Basically what I need is to get category_name and parent_category_name for each post in response for /wp-json/wp/v2/posts
Under categories it only returns array of category IDs. That's not an option since there is a lot of categories and subcategories to map all that stuff.
With parameter _embed I can get "wp:term" but it's not exactly what I need. It returns arrays of categories and tags both combined and sometimes it won't return the parent category.
Any solutions? Should I keep going on through the documentation or is there any function to extend the WordPress REST API response?
There are quite a few ways to manipulate the WP Rest API with the information you need.
One way would be to filter the post object in REST directly, using the rest_prepare_{$post_type} filter
Another would be to register a new "REST field" with the register_rest_field function.
Using the first one, you could do something as simple as getting the category names and dropping them in as a new data field:
add_filter( 'rest_prepare_post', 'my_filter_post', 10, 3 );
function my_filter_post( $data, $post, $context ){
// Does this have categories?
if( !empty($data->data['categories']) ){
// Loop through them all
foreach( $data->data['categories'] as $category_id ){
// Get the actual Category Object
$category = get_category( $category_id );
if( $category->parent == 0 ){
// "top level" category
$data->data['parent_category'] = $category->name;
} else {
// some child level category
$data->data['child_category'] = $category->name;
}
}
}
return $data;
}
Using the REST field option would look something like this WPSE answer, though you'd of course need to iterate over the categories to see which is the parent and which is the child, etc.
In either case, you may need to adjust the logic and use something like the get_ancestors() function or one of the many "get hierarchical cat/terms" answers, especially if you've got more than a "parent > child" relationship, or multiple levels of categories on each post - but rest_prepare_{$post_type} or register_rest_field should be able to get your desired result pretty easily.
I have an advanced custom field set up to show on a woocommerce subcategory that allows the user to define a colour via the color picker field.
This field will apply that colour to a number of elements related to that sub category (Styling the sub category thumbnail, the product page itself etc).
Im currently using as per the the ACF documentation this code to pull the field in and display it on the subcategory page:
$term = get_queried_object();
$color = get_field('colour', $term); // Get ACF Field
This works fine until it comes to the parent category for the sub pages. I am unable to call the field in for the sub categories of the parent. I understand I need to use get_terms(). I am unable ot get that working though.
This is some code I found which I have added to the loop on content-product_cat.php. However it just breaks the woocommerce loop. What would I need to do to this code to get the parent category page to show all the child subcategories each with its related color field?
// current term
$current_term = get_queried_object();
// child terms
// this returns an array of terms
$args = array(
'taxonomy' => 'YOUR TAXONOMY HERE',
'parent' => $current_term->term_id,
// you may need other arguments depending on your needs
);
$child_terms = get_terms($args);
// you need to maybe loop through the child terms gotte
// to pick which one you want to use
// I'm assuming that you only want to use the first one
$child_term = false; // set it to false to begin with
// we'll use this later
if ($child_terms) {
$child_term = $child_terms[0];
}
// make a decision
if ($child_term) {
// get field value(s) from child term
$color = get_field('color', $child_term);
} else {
// get field value(s) from current term
$color = get_field('color', $current_term);
}
// do something with the values
echo $color;
I found the solution here:
https://wordpress.stackexchange.com/a/341632
add_action('woocommerce_after_subcategory_title', 'wpse_add_custom_text_under_category_title', 10);
function wpse_add_custom_text_under_category_title($category) {
$term_id = 'product_cat_'.$category->term_id;
the_field('krotki_opis_kategorii', $term_id);
}
From Alex Uleberg:
get_queried_object_id on shop archive page it will return the id of the page and not the category. When you use the hook, the $category object will be passed in through the hook.
I have Two parent category on my website, and each of those category have children category, like this :
constructions corollaires
01
02
03
04
Between two suns
I
II
III
IV
I'm trying to display the parent category on a archive page, and also the children category.
here is my code for the parent category :
<?php
$category = get_the_category();
echo $category[0]->name;
?>
and for the children category :
<?php
$category = get_the_category();
echo $category[1]->name;
?>
what I don't understand, is that for posts who are in inside "Between two suns" category, first code echoes "Between two suns" which is the correct value, but posts who are inside "constructions corollaires", it echoes "I", the sub category instead of "constructions corollaires".
and it's the same problem with my second code, for posts who are in inside "Between two suns" category, second code echo "I" which is the correct value (1st children category), but posts who are inside "constructions corollaires", it echoes "constructions corollaires", the parent category instead of "01" for example (the children category.
I don't understand what I'm doing wrong...
all my categories are sorted in the back end.
can anybody help me with this ? It looks like an ordering issue but I really don't know how to fix this !
For only Top label category
$categories = get_terms(
'category',
array('parent' => 0)
);
And get children category just pass parent category id in parent item
$categories = get_terms(
'category',
array('parent' => $cat->ID)
);
My wordpress site has categories with a simple hierarchy –
Blog
Role Shift
Urod the Last Show
News
I'm using the if statement below to catch if the post is in category blog or any of the child categories - and it works - but it feels stupid not to be able to just check the parent of the current category (plus I might want to add categories later).
if ( is_category('blog') || in_category(array('role-shift', 'urod-the-last-show', 'news')) )
I've searched and tried every suggestion - including cat_is_ancestor_of - but nothing is working.
Please help!
Robert
$categories = get_the_category(); //returns categories
$thiscat = $categories[0];
$parent_id = $thiscat->parent; //the parent id
$parent = get_category($parent_id) //this returns the parent category as an object
//use id or slug of category you are searching for
if( $parent_id == 1 || $thiscat->slug == 'blog' ){
//this is a child of blog or the blog page
}
This should do the trick.
This will determine if the current category is a child of the blog page.
The first part, get_category, returns the current category.
Then you can get the parent id from the current category and use 'get_the_category_by_ID' to get the parent category object.
Then you can check if you are under the parent category you want.
I having been searching for days to get the last subcategory of a product in magento.
Actually what i have to do is display the last subcategory the product is placed in. for example i have plastic and glass as products. I want to display the last subcategory i.e cups or plates.
|Party
--|boys
----|batman
--------|cups
-----------|plastic
-----------|glass
--------|plates
----|Superman
i have edited the list.phtml file, i can get the category id's and name from the array but they are all mixed up. So there is no way to figure out which one is the last category.
Is there any default functionality in magento? or someone be kind enough to help me out?
Thanks in advance.
Edit
Okay, from your description it sounds like you want to get the child categories from the current category you're in. (I.E. Get cups and plates while in batman category view).
The following should be just about as little as you need to get the current children.
<?php
$_helper = Mage::helper('catalog/category');
$children = Mage::registry( 'current_category' )->getChildrenCategories();
?>
<ul>
<?php foreach( $children as $child ): ?>
<li><?php echo $child->getName() ?></li>
<?php endforeach; ?>
</ul>
Previous Answer(s)
It's a little roundabout, but this can get you the parent category id from a product object.
//If you don't have a product to start with, load by ID.
$_product = Mage::getModel( 'catalog/product' )->load($id);
//Assign Category Model
$categoryModel = Mage::getModel( 'catalog/category' );
//Get Array of Category Id's with Last as First (Reversed)
$_categories = array_reverse( $_product->getCategoryIds() );
//Get Parent Category Id
$_parentId = $categoryModel->load($_categories[0])->getParentId();
//Load Parent Category
$_category = $categoryModel->load($_parentId);
//Do something with $_category
echo $_category->getName();
It works better when the product only has one category Id assigned to it. You may not get the category you want if multiple categories have been assigned to that one product.
Also, you can get it a slightly quicker way, but this method doesn't work if the product was searched for:
$_category = Mage::getModel( 'catalog/category' )->load( Mage::registry( 'current_category' )->getParentId() );
I didn't test the line above, but it should work. Only if the product was reached by browsing through the categories though.