I am trying to get 2nd level category of a single Post.
A Post is under this hierarchy Sports > Football > premier league
i want to get the ID for Sport how can i do this.
Thank You.
You can get all first level categories by this code for particular post
$cat = get_the_category($post_id);
then by this one you can get child categories
$child_categories=get_categories(
array( 'parent' => $cat->cat_ID )
);
Try this, this will work for 'nth' level
$category = get_the_category();
$parent = get_ancestors($category[0]->term_id,'category');
if (empty($parent)) {
$parent[] = array($category[0]->term_id);
}
$parent = array_pop($parent);
$parent = get_category($parent);
if (!is_wp_error($parent)) {
var_dump($parent);
} else {
echo $parent->get_error_message();
}
Reference:
get_the_category
get_ancestors
Related
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've found numerous posts regarding people pulling the slug or the ID of a WordPress post's top category, but I need to pull the name specifically.
Here's the current structure:
Spring 2016 (slug 2016-spring)
Feature (feature)
Giving Highlights (giving-highlights)
etc.
The code I have works perfectly in pulling the top level slug/nicename (2016-spring), but I need it to return the name/cat_name (Spring 2016) instead.
The code I'm using is:
$category = get_the_category();
$cat_tree = get_category_parents($category[0]->term_id, FALSE, ':', TRUE);
$top_cat = split(':',$cat_tree);
$parent = $top_cat[0];
echo $parent;
What do I need to change in order to be pulling the name?
Here's a solution I use in my current environment:
$categories = get_the_category();
if ( ! empty($categories)) {
if (sizeOf($categories) > 1) {
$output = $categories[1]->name;
} elseif (sizeOf($categories) == 1) {
$output = $categories[0]->name;
} else {
$output = 'Please Assign A Category';
}
}
We have situations where some posts only use the top level category, while others use a deeper category within that for sorting purposes. Your situation will obviously vary; if all your posts will be at least 1 deep within the tree, you can just use the $output=$categories[1]->name; line and that will be fine. Ours is a bit more robust just in case.
Why not try to simply pull the category name of the parent using get_category() ?
Try this
$parent = $top_cat[0];
$pcat = get_category( $parent ) ;
// Then
echo $pcat->cat_name ;
// OR
echo $pcat->category_nicename ;
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.
I'm displaying the 3 most recent posts from a parent category ("Where We Serve") on a page. Within that parent category, I have 6 other categories named by regions ("Africa", "Europe", "Asia", etc.). The page displays the region category name, and the post content below it. Here's the catch; of these 3 most recent posts, sometimes there will be 2 from the same region category. When that happens, I need the page to show the region category for ONLY the first post from that category. Hopefully this code explains what I'm trying to do:
<div class="news">
<?php
$args = array( 'numberposts' => '3', 'category' => 9 );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ){
$category = get_the_category($recent["ID"]);
if(
$category == //any previous post's category on this page
){
//echo the post WITHOUT the category name displayed
echo '<h2>'.$recent["post_title"].'</h2><br>'.$recent["post_content"].'<br>';
}
else{
//echo the post WITH the category name displayed
echo '<h1>'.$category[0]->cat_name.'</h1><br><h2>'.$recent["post_title"].'</h2><br>'.$recent["post_content"].'<br>';
}
}
?>
</div>
I don't know how to test for other posts' categories on that page.
As you loop through the posts, save the categories you have used to an array, then check that array to see if the category already exists.
$used_categories = array(); //optional, but for clarity
foreach( $recent_posts as $recent ){
$category = get_the_category($recent["ID"]);
$category_name = $category[0]->cat_name;
if(!isset($used_categories[$category_name])){
//echo the category name displayed
echo '<h1>'.$category_name.'</h1><br />';
//save to used categories. Value assigned doesn't matter
$used_categories[$category_name]=true;
}
//You are outputting this either way, so take it out of the if
echo '<h2>'.$recent["post_title"].'</h2><br />'.$recent["post_content"].'<br />';
}
EDIT: I'm now using Eric G's method.
I wasn't able to get this to work with PHP. I ended up using this javascript at the bottom of the page:
var regionName = document.getElementsByTagName("h1");
if(regionName[1].innerHTML == regionName[0].innerHTML){
regionName[1].style.display="none";
};
if(regionName[2].innerHTML == regionName[1].innerHTML){
regionName[1].style.display="none";
};
Definitely not as clean or "correct" as I was hoping, but it's working for now...
I need a small line of code. I have a category like
Cat-1
Sub-Cat-1
Sub-Cat-2
Cat-2
Sub-Cat-3
Sub-Cat-4
In Sub-Cats page i need to get Root category's Id. Like In "Sub-Cat-1" i need to get "Cat-1's" ID. You can say in children category page, i need parent category's Id. act i am using short url like "abc.com/Sub-Cat-1", nither index.php nor root category in URL.
I am using Magento-1.4.1. Please help me. Thanks in advance.
I got the solution.
echo $cat_idd = $this->getCurrentCategory()->getParentCategory()->getId();
Try to use as:
echo $subCategory->getParentId();
// to get the category ID by product id
$productObj = Mage::getModel('catalog/product')->load($product_id);
$categoryIds = $productObj->getCategoryIds();
//Display all categories.
function get_categories(){
$category = Mage::getModel('catalog/category');
$tree = $category->getTreeModel();
$tree->load();
$ids = $tree->getCollection()->getAllIds();
$arr = array();
if ($ids){
foreach ($ids as $id){
$cat = Mage::getModel('catalog/category');
$cat->load($id);
$arr[$id] = $cat->getName();
}
}
return $arr;
}
$arr = get_categories();
$arr = array_flip($arr);
//print the array
Hope it will help someone.