Wordpress get category parents as category array - php

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!!!

Related

Return to subcategory not in the parent

I have added a function in the functions.php file, so when the user clicks a button, the user will return to the previous category page of the product that belongs to even if it is in subcategory or not.
The problem is that in my current function when i navigate to a product, the function returns me to the parent category, not in the sub.
- Category
|-> Sub Category
|-> Product
The function
function previous_next_product(){
echo '<div class="prev_next_buttons">';
// Get parent product categories on single product pages
$terms = wp_get_post_terms( get_the_id(), 'product_cat', array( 'include_children' => true ) );
// Get the first main product category (not a child one)
$term = reset($terms);
$term_link = get_term_link( $term->term_id, 'product_cat' ); // The link
echo '<i class="fa fa-bars" aria-hidden="true"></i>';
// 'product_cat' will make sure to return next/prev from current category
$previous = next_post_link('%link', '←', TRUE, ' ', 'product_cat');
$next = previous_post_link('%link', '→', TRUE, ' ', 'product_cat');
echo $previous;
echo $next;
echo '</div>';
}
You can use get_category to get category object, and can easily extract slug or any other information needed.
Here's example code:
//load data of your child category
$child = get_category(CHILD_CATEGORY_ID_HERE);
//from your child category, load sub parent object
$sub_parent = get_category($child->parent);
//load parent from your sub parent
$parent = get_category($sub_parent->parent);
//extract slug like this
echo $sub_parent->slug; //will print slug of sub parent
And to check, if category has parent, you can use this:
if($child->parent){
//extract subchild slug here
//can do similar check for parent, if exists then extract parent object info
}
By using this code, you can extract:
Child
Sub Parent
Parent
Hope it helps! :)

Wordpress ACF - How to get field from category page

I have a website with several categories and now I'm implementing the languages and I need to add a custom field to category page but I can't get the field.
So this is my custom field:
Next I go to category page and introduce the text in each language.
In my code I do this:
<?php
$obj = get_queried_object();
$ar = array('child_of' => $obj->term_id);
$categories = get_categories( $ar );
foreach($categories as $category) {
$custom_field = get_field('descricao_traducoes', $obj->term_id);
var_dump($custom_field);
}
?>
But returns me null.
How can I do that?
I think you're just passing the wrong variable as a second parameter in get_field!
Do $category->term_id instead.
(Unless you meant to dump the descricao_traducoes of the queried object for as many times as there are categories)
<?php
$obj = get_queried_object();
$ar = array('child_of' => $obj->term_id);
$categories = get_categories( $ar );
foreach($categories as $category) {
$custom_field = get_field('descricao_traducoes', $category->term_id);
var_dump($custom_field);
}
From the ACF docs:
get_field($selector, [$post_id], [$format_value]);
$selector (string) (Required) The field name or field key.
$post_id (mixed) (Optional) The post ID where the value is saved. Defaults to the current post.
$format_value (bool) (Optional) Whether to apply formatting logic. Defaults to true.

Get the parent product categories ids from a sub product category ID in Woocommerce

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');

get_terms function to return all child categories not returning all results

I'm trying to get a given category's child categories like so:
$this->getChildCategories = function($parent_id) {
$args = array(
'parent' => $parent_id,
);
$terms = get_terms('category', $args);
return $terms;
};
When having a look in the dashboard, there are 10 child categories in total. However the function only returns 5 results.
You seem to be calling the function in a wrong way. If you refer the function in the documentation, here's how it is called:
get_term_children( $term, $taxonomy );
So to get the children categories of a category, here's what we gotta do:
get_term_children( $term, $taxonomy ); //where $term is "category_id" and $taxonomy is "category"
Since you have slug not the id of the parent category, you can obtain the id by this function:
$parent_category = get_category_by_slug('category-slug');
$parent_category_id = $parent_category->term_id;
Using the above functions to write our own function to get the children categories:
function get_children_categories($category_slug, $taxonomy_name){
$parent_category = get_category_by_slug($category_slug);
$parent_category_id = $parent_category->term_id;
//$Uncategorized_id = get_cat_ID('Uncategorized') ;
$children_categories = get_term_children( $parent_category_id, $taxonomy_name);
//unset($children_categories[$Uncategorized_id]);
return $children_categories;
}
The above functions also returns "uncategorized", so to remove that you can uncomment the commented part in the above function.
You can call the function get_children_categories by passing the parameters:
get_children_categories('event', 'category') //shall return all the children category ids.
Now you have all the children category ids of the category passed. To get the term object, you can use the following function:
get_term_by( $field, $value, $taxonomy, $output, $filter )
Thank.
P.s: I had to personally search you since you deleted your last question. This however is the answer to your last question.
You need to disable default limitation:
'numberposts' => -1,
You can pass the parent category ID instead of $cat->cat_ID.
$categories=get_categories(
array( 'parent' => $cat->cat_ID )
);

Turn Woocommerce category ID into slug function

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.

Categories