Wordpress - Get Current Category Parents - wordpress

In category.php, how would I test against a category having a parent category?
If the parent category is A, and the sub-category is B, and the user loads the URL for category B, I would like to be able to test if it has parent A, and run code if it does.
I've found the get_category_parents tag, but it seems to return a link list rather than an array:
get_category_parents($cat, TRUE, ', '));
Even if I got the array, I'm not sure what the php function is to test against it (php noob).
Thanks!

You can use the cat_is_ancestor_of function to check if a category is a child of another category. For example to check if the current category is a child of a category named 'blog':
cat_is_ancestor_of(get_cat_id('blog'), get_query_var('cat'))

First, you have to get current category's id:
$category_id = get_query_var('cat');
Then you can make a database query to see it has a parent or not:
$parent = $wpdb->get_var("SELECT parent FROM ".$wpdb->prefix."term_taxonomy WHERE term_id = $category_id");
If it has one, $parent will contain one-level-above parent's id and naturally it's value should be greater than 0, so you can check this like below:
<?php if ($parent > 0 ) : ?>
// do something
<?php endif; ?>
You can use $parent however you want;
$parent_link = get_category_link( $parent );
$parent_name = get_cat_name( $parent );
// etc.
If you want to see that there is more high-level parent's, you can do the same things(db query) with parent's id or even write a recursive function that go to until top level. As i saw in the source code, built-in get_category_parents() function do it like that.
HTH

Check out the reference page for get_category_parents, you are asking for links when you set the second parameter to TRUE.
You should be doing:
get_category_parents($cat, FALSE, ', '));
I also recommend not using spaces as separators, since you will probably need to trim those spaces later.

Related

Wordpress - custom template page for a parent category and all child categories

In WP 5.4.2 I want to create a custom archive page for a category and all it's child categories. I am aware of the template file hierarchy:
1. category-slug.php
2. category-ID.php
3. category.php
4. archive.php
5. index.php
but if I understand correctly and if I did all the testing right, the category-slug.php, or the category-id.php scheme applies to a single category regardless of the category hierarchy.
Let's say I have following categories:
colors (id 2)
- red (id 10)
- green (id 11)
- blue (id 12)
I need a single template file for all of them. Simply creating category-colors.php or category-2.php doesn't work. It applies to the single category (colors) only. I want it to apply to all the current child categories, as well as all the child categories I add in the future. Is it possible? If so, please advice how.
There are a couple of ways to do this, but using the category_template filter to let you use a custom category template seems the most common.
The function below will let you dynamically check back through the parent levels of the current category until it finds a template called "category-[parent slug]" for the closest ancestor category or it reaches the top level - whichever is first.
Suppose you have something like:
- products
- hardware
- food
- dairy
- vegetables
On the dairy page, it will first check if you have a slug called category-dairy.php.
If you do, it will return it.
If you don't, it will look for category-food.php.
If that's not found, it will look for category-products.php.
Add this to your functions.php - this is untested by the code is well commented so you can understand how it works:
function get_template_for_category( $template ) {
if ( basename( $template ) === 'category.php' ) { // No custom template for this specific term, let's find it's parent
// get the current term, e.g. red
$term = get_queried_object();
// check for template file for the page category
$slug_template = locate_template( "category-{$term->slug}.php" );
if ( $slug_template ) return $slug_template;
// if the page category doesn't have a template, then start checking back through the parent levels to find a template for a parent slug
$term_to_check = $term;
while ( $term_to_check ->parent ) {
// get the parent of the this level's parent
$term_to_check = get_category( $term_to_check->parent );
if ( ! $term_to_check || is_wp_error( $term_to_check ) )
break; // No valid parent found
// Use locate_template to check if a template exists for this categories slug
$slug_template = locate_template( "category-{$term_to_check->slug}.php" );
// if we find a template then return it. Otherwise the loop will check for this level's parent
if ( $slug_template ) return $slug_template;
}
}
return $template;
}
add_filter( 'category_template', 'get_template_for_category' );
References:
WP Codex category_template Reference
WP Developer locate_template Reference
Make categories use parent template

Woocommerce override grouped product title

I've seen this on other themes but can't work out how it has been done. In my grouped product list, the title lists as Parent product title --> Child product title. I need it only to list the Child product title.
I can see the code to alter is:
' . $child_product['product']->post->post_title . '
Either the post_title needs to overridden, or the code altered to...what?
(Although this is old, it's still a common question with a prominent google ranking)
Woocommerce defines a filter, woocommerce_product_title, which allows you to pass a product's title through a function that modifies the way it will display.
Add a filter, probably in your theme's functions.php
add_filter('woocommerce_product_title', 'clean_up_title');
This is the function I'm currently using to accomplish this, no promises that it's the best way possible:
function clean_up_title($title){
// check to see if there is an html arrow in the title
if (strpos($title, '→')){
$separator = '→';
}
// otherwise assume it's the character
else {
$separator = '→';
}
// split the title into multiple parts at the arrows
$prog_array = explode($separator, $title);
// get the last part, the actual product name
$prog_name = end($prog_array);
// slice off any leading or trailing whitespace
return trim($prog_name);
}
This would be a bit cleaner to do. Just 'return' the product title rather than 'edit' it.
function clean_product_title($title, $product) {
return $product->post->post_title;;
}
add_filter('woocommerce_product_title', 'clean_product_title', 10, 2);

Wordpress menu items order

basically I have a three-level menu in wordpress and I've got the following code in the front-end to call the third-level menu:
$children = get_pages('child_of='.$include_page_ids[$i]);
if (count($children) > 1) {
$sub = "<ul>";
foreach ($children as $child){
$sub .= "<li><a href='#$child->post_title'>";
$sub .= $child->post_title;
$sub .= "</a></li>";
}
$sub .="</ul>";
echo $sub;
}
This calls a list for the children of a certain page and also makes the the anchors (which I also need). The problem is that right now they are being displayed in an alphabetical order, but I need to be able to set the right order myself (ie to be the same as in the backend menu). Please hepl me with it, how can I achieve this? For example this is the page http://www.eboxlab.net/transbeam/support/support/, youcan see the third level-menu as the box right next to the banner (Acceptable Use Policy to Terms & Conditions). THe order of the blocks which it corresponds to is right, but the menu is alphabetically ordered.
Help really appreciated.
PS: if you need I can provide the template code
It's pretty simple actually. Here is what your $children call should look like:
$children = get_pages('child_of=' . $include_page_ids[$i] . '&orderby=menu_order&sort_order =ASC');
That's all you need to add - this tells the query to order pages in ascending fashion by their "menu_order" column(or the "Order" field under Page attributes). You can see more details on the get_pages function at Function Reference/get pages
wp_nav_menu to the rescue! Assuming you're using WP 3 or newer, it will let you wrap elements in whatever markup you'd like, and will correspond to however you've configured the menu in the admin Dashboard.

Tag list Drop Down Menu

I am wondering how to create a simple tag drop-down menu (all tags included DESC) without rewriting the WP core functions. It has to work outside of any loop.
wp_tag_cloud() with the 'format=array' attribute would seem the best choice since it works outside of any loop/template and returns all available tags sorted A-Z (which I need) but the array values contain HTML formatting (instead of just a plain string value) and that is not suitable for creating the drop-down.
i.e.:
<?php $tag = wp_tag_cloud('format=array'); // 'format=array' contains <a>link</> !!!
foreach($tag as $tagkey => $tagvalue) // ...need to be somehow filtered out !!
{
echo "<option value='".$tagvalue."'>".$tagvalue."</option>";
}
?>
The get_the_tag_list() function works great but it doesn't work outside of the template (loop).
Is there a simple way how to get the list of all tags so I can put them into the drop-down?
...OMG! I can't believe I actually asked this publicly!
Of course the code is ...
<?php $tag = wp_tag_cloud('format=array' );
foreach($tag as $tagkey => $tagvalue)
{
$cleanedup = strip_tags($tagvalue);
echo "<option value='".$cleanedup."'>".$cleanedup."</option>";
}
?>

How do I get the parent category name in WordPress template? And can I query post by the parent category?

I tried getting help on the WordPress forums but no luck. Anyways, here is my question...
Lets say I am creating 10 parent categories and 2 sub categories to each parent. My WordPress post belongs to one sub category of a particular parent category
How do I get the parent category name ONLY? I don't want subcategories names? what WordPress code would do that?
And one more question...
Is it possible to query post by the parent of a sub category by using:
but instead of entering cat=1 or the name of the particular category, can I do something like:
So this way it would automatically insert and query post for the parent of any particular sub category that's clicked on?
To get the parent category name, use the get_cat_name() function, with the parent as the parameter -- like so:
$cat = get_the_category();
$parentCatName = get_cat_name($cat[0]->parent);
All these answers failed for me.
I eventually managed to display a post's topmost category name like this :
$categories = get_the_category();
$category= '';
foreach($categories as $childcat) {
$parentcat = $childcat->category_parent;
if($parentcat>0){
$category = get_cat_name($parentcat);
continue;
}
}
$category = (strlen($category)>0)? $category : $categories[0]->cat_name;
Found this answer, which gives you the first ancestor slug. It could easily be modified to give you the name.
Got it here: http://nick.boldison.com/wordpress/wordpress-get-top-level-parent-category/
<?php
// get parent category slug
$parentCatList = get_category_parents($cat,false,',');
$parentCatListArray = split(",",$parentCatList);
$topParentName = $parentCatListArray[0];
$sdacReplace = array(" " => "-", "(" => "", ")" => "");
$topParent = strtolower(strtr($topParentName,$sdacReplace));
?>
In fact, to get the parent name:
// get parent category slug
$parentCatList = get_category_parents($cat,false,',');
$parentCatListArray = split(",",$parentCatList);
$topParentName = $parentCatListArray[0];
Lots of answers and examples in the Wordpress docs:
get category parents
get the category
(And it looks like some code snips or other text didn't come through in your original question)

Resources