Wordpress categories hierachy issue - wordpress

I have problem with my catogories in my custom post type. I am trying to do a basic apartments booking system. I created custom post called Apartments and then I added a categories. The category tree looks like this:
Countries
- Spain
-- Barcelona
-- Madrid
- Greece
-- Athenes
and so on.
I want to achive effect when the user enter to the apartment in Barcelona, the higher category will be displayed in header (in this example Spain). When the user eneter to the apartment in Athenes the Greece category should be in header. I tried solution that I have found on stack but it does not work for me.
$category = get_the_category();
foreach ($category as $cat) {
echo $cat->name;
}
$ancestors = get_ancestors( $category[0]->term_id, 'category' );
$direct_parent_id = $ancestors[0];
echo $direct_parent_id;
Only the second category is displayed and as you can see the categories are displayed in alphabetical order instead of hierarchical.
I hope you understand what I mean.
Thank you in advance for directions

Function get_the_category returns the object WP_Term. So, it's possible to get the parent from that object.
Used this answer, in your case it will be:
First, add this function to your functions.php file of active theme/child theme to have access to it from other files of theme/child theme:
function get_deep_child_category( $categories )
{
$maxId = 0;
$maxKey = 0;
foreach ( $categories as $key => $value )
{
if ( $value->parent > $maxId )
{
$maxId = $value->term_id;
$maxKey = $key;
}
}
return $categories[$maxKey];
}
Note: in some cases this will not work as expected. For example, if your post has category Some_category, which is child of Some_category_parent, and the Some_category_parent was created after your Spain category, then, this will return the category Some_category.
Next step will be to use it. For example, in your post template:
$categories = get_the_category();
if ( $categories ){
$deep_child = get_deep_child_category( $categories );
echo get_cat_name($deep_child->parent);
}
After getting the deepest category object with function get_deep_child_category, we got the ID of it's parent category. get_cat_name() returned the name of parent category using it's ID. In your case, it's Spain.

Related

Wordpress - setting a custom post per category

I have added the below code to the functions.php file to load different post templates per category. The code is doing what it is supposed to do. The issue I am facing is that when I open posts these load correctly but whilst loading an error is displayed for a instant saying "trying to get property of non-object in .......functions.php" How may I get rid of that error? Appreciate your help.
/* ----------------------------------------------------------------------------
custom single posts per category
*/
add_filter('single_template', 'check_for_category_single_template');
function check_for_category_single_template( $t )
{
foreach( (array) get_the_category() as $cat )
{
if ( file_exists(get_stylesheet_directory() . "/single-category-{$cat->slug}.php") ) return get_stylesheet_directory() . "/single-category-{$cat->slug}.php";
if($cat->parent)
{
$cat = get_the_category_by_ID( $cat->parent );
if ( file_exists(get_stylesheet_directory() . "/single-category-{$cat->slug}.php") ) return get_stylesheet_directory() . "/single-category-{$cat->slug}.php";
}
}
return $t;
}
The error trying to get property of non-object means, you try to get a property of something that is not an object. So looking at your code you are getting two properties with ->: "slug" and "parent".
This gives us the hint, that the value saved in the $cat variable might not be an object.
You are using get_the_category_by_ID which gives you a name, not a category object. https://developer.wordpress.org/reference/functions/get_the_category_by_id/ So you cannot access any property. The problem is this: get_the_category_by_ID( $cat->parent ); There is no parent property in $cat, because it only contains the name. You need to get the object to make use of the parent property. Moreover the property is called category_parent, and not parent.
$parent_id = $cat->category_parent;
$cat = get_category($parent_id);
This should solve your problem.
If it does not solve your problem, I wrote the code in another way. It shows single steps and maybe it is useful for you or some other users.
The function to get all your category objects is: get_categories() https://developer.wordpress.org/reference/functions/get_categories/
You can save all the IDs of the categoires into a array. After that, you loop through each position of the array and check if the single post you are viewing has the same category ID. We can check if the post is in given categories using in_category() https://developer.wordpress.org/reference/functions/in_category/
I did no testing, but the code can look something like:
add_filter('single_template', 'check_for_category_single_template');
function check_for_category_single_template() {
// Get all category objects
$categories = get_categories();
// Array for IDs
$categories_ids = [];
foreach($categories as $category) {
// add id to array
array_push($categories_ids, $category->cat_ID);
}
// Loop through array of IDs
foreach($categories_ids as $category_id) {
// Check if ID equals current post category ID
if ( in_category($category_id) ) {
// get current category object
$cat = get_category($category_id);
// check if category has parent
if( $cat->category_parent > 0 ) {
$parent_id = $cat->category_parent;
// get parent object
$cat = get_category( $parent_id );
}
// get slug of category
$cat_slug = $cat->slug;
if ( file_exists(get_stylesheet_directory() . "/single-category-" .$cat_slug. ".php") ) {
return get_stylesheet_directory() . "/single-category-" .$cat_slug. ".php";
}
}
}
}

WooCommerce Product Category Description

I don't get it!!! I have managed to include the product category description in their respective pages. I have 6 categories which with four of them I need to add a description. From the four, three worked as it should. However, there is one of them that not only shows its description but also another category's.
There are two of each category for multiligual purpose. But you can see the four categories I need to add the description.
1 - Tops
2 - Bottoms
3 - One Pieces
4 - Sport Wear
The first three worked as it should. Ie. Bottoms category page.
But the fourth, Sport Wear keeps showing not only its description but also the Top category's as well.
I have already recreated the category Sport Wear, but it remained the same way. I have no clue why this is happening. Any idea would be very much appreciated.
Here is the link: https://morenabeachwear.com/en/product-category/sport-wear/
And here the code I used to loop and display description.
function action_woocommerce_archive_description( ) {
global $post;
$args = array( 'taxonomy' => 'product_cat');
$terms = wp_get_post_terms($post->ID,'product_cat', $args);
foreach ($terms as $term) {
if (is_product_category()) {
echo $term->description;
}
}
};
add_action( 'walker_edge_after_page_title','action_woocommerce_archive_description', 10, 2 );
It turned out I didn't need the loop. And made sure to echo the first item of the array returned from wp_get_post_terms
function action_woocommerce_archive_description( ) {
global $post;
$terms = wp_get_post_terms($post->ID,'product_cat');
if (is_product_category()) {
echo $terms[0]->description;
}
};
add_action( 'walker_edge_after_page_title', 'action_woocommerce_archive_description', 10, 2 );

WordPress get category ID from URL

I have hard time trying to find the solution, does somebody know how to get this:
I have one WordPress post in more than one category, but only one is permalink category. I need to get the ID only of that permalink category (I need this info so I can take few latest posts from permalink category via custom query).
url looks like this http://domain.com/category-name/post-title
I need that "category-name" ID.
A Good one to use is:
<?php $page_object = get_queried_object(); ?>
<h1><?php echo $page_object->cat_name; ?></h1>
global $wp;
$current_url = home_url( add_query_arg( array(), $wp->request ) ); get url
$url_array = explode('/',$current_url);
$retVal = !empty($url_array[5]) ? $url_array[5] : $url_array[4] ;
$idObj = get_category_by_slug($retVal);
echo $idObj->name
My answer is:
function get_category_by_url($url) {
foreach( (get_the_category()) as $category) {
if ( get_category_link($category->cat_ID) == $url )
return $category->slug;
}
return false;
}
$category = end(get_the_category());
$current = $category->cat_ID;
echo 'id='.$current . ' - name=' . $category->cat_name;
If the post belongs to many categories, what if you're viewing the post from a second category. In that case retrieving the category ID of the permalink category may not help, since you would need the related posts of the current category in action.
For that, you can get the ID by passing the category name as follows:
<?php get_cat_ID($cat_name)?>
Does this help?
Wordpress chooses the oldest category as the permalink category. There's no way to change that behavior unless you use some plugin. If you choose to use a plugin you make take the category ID from plugin settings.
You can list all categories of this post and choose most relevant category.
Use the following code inside The Loop:
foreach((get_the_category()) as $category)
{
if ( $category->cat_ID == 1000 )
; // DO SOMETHING
}

Show the_content() from specific category

I need to find out how to list my content data on a page/ section when I click on a specific category link.
After a few hours I realise that help from stackoverflow is what i need!
The function remind a little of: http://www.hashbangcode.com/blog/wordpress-category-post-list-493.html
I need to list my data (title, the_content etc) from the specific category and not all categories with the titles.
While that post gives you a good start, here is the code that I would use
// Set the desired category
$category = 1;
// Make query for posts in the category
$my_query = new WP_Query();
$my_query->query(
array(
'cat' => $category,
// Does not show sticky posts; use 'caller_get_posts' if using < WP 3.1
'ignore_sticky_posts' => 1
)
);
// Make sure some posts were found.
if($my_query->have_posts())
{
// Loop through each post found.
while($my_query->have_posts())
{
// Setup the post data to use
$my_query->the_post();
global $post;
// Echo out the title; Note that no formatting has been done
the_title();
the_content();
}
}
Now, you can also get the title with either:
$title = get_the_title($post->ID);
$title = $post->post_title;
Additionally, you can get the post content with:
$content = $post->post_content;
Also, you can get the category using any of these parameters:
cat (int) - use category id.
category_name (string) - use category slug (NOT name).
category__and (array) - use category id.
category__in (array) - use category id.
category__not_in (array) - use category id.
More about the WP_Query class can be found here: http://codex.wordpress.org/Function_Reference/WP_Query

wordpress categories: how to find the last child category for a post

I have a category structure that is 5 levels deep. when returning the categories for a post, these categories are not in any particular order. I need to find the last child category for a post.
$categories = get_the_category();
$last_category = $categories[0];
foreach($categories as $i => $category)
{
if($category->parent == $last_category->cat_ID)
{
$last_category = $category;
}
}
You might want to try wp_get_object_terms
If you have the $post_ID, just call wp_get_object_terms($post_ID). It returns an array with every category for that post, referencing parents and children.
If you are using them in the loop, you could try this:
<?php the_category("", "single"); ?>
Ref: the_category
===== UPDATED =====
Outside the loop:
<?php the_category("", "single", $post->ID); ?>

Resources