How to Check Which level category it is for wordpress? - wordpress

Let me tell you the scenario first say the structure of the categories in wordpress is like this
Level 1: Top
Level 2: -Nextme_1
Level 3: --Nextme_2
--Nextme_3
Level 4: ---Nextme_4
---Nextme_5
Now I require to check what is the level of the category? Say I catch a category of level 3 so I have to use different template and if its level 4. Then I need to use another template?
Anybody can give me some hint?
Thanks
Rahul

If you don't have many categories you can try to edit their slug from admin, and then in your page you get the category slug this way:
if (is_category()) {
$cat = get_query_var('cat');
$category = get_category($cat);
echo 'your slug is '. $category->slug;
}
Now, when you're editing the categories slugs try naming them after their level: cat-lvl-1, cat-lvl-2. Then in your page you extract the number from category slug using some php string function, and then you check that number:
if ($category->slug == 1 ) {
//load the template for the category of level 1
}
if ($category->slug == 2 ) {
//load the template for the category of level 2
}
and so on.
Later edit:
Try this:
function get_level($category, $level = 0)
{
if ($category->category_parent == 0) {
return $level;
} else {
$level++;
$category = get_category($category->category_parent);
get_level($category, $level);
}
}
if (is_category()) {
$cat = get_query_var('cat');
$yourcat = get_category($cat);
echo get_level($yourcat);
}

You can call the get_ancestors() function to get an array containing the parents of the given object. Then you need to count elements in the result.
function get_the_level($id, $type = 'category') {
return count( get_ancestors($id, $type) );
}
if( is_category() ) {
$level = get_the_level( $cat );
}
elseif( is_product_category() ) {
$level = get_the_level( $wp_query->get_queried_object()->term_id, 'product_cat' );
}

Thanks a lot. This is superb with slight a change the code that you have written is fine but its not returning any value.(i,e the $level) although its calculating correct. A minor change i did and its work fine now with a slight editing of you code given below..
`
function get_level($category, $level = 0)
{
if ($category->category_parent == 0) {
return $level;
} else {
$level++;
$category = get_category($category->category_parent);
return get_level($category, $level);
}
}
if (is_category()) {
$cat = get_query_var('cat');
$yourcat = get_category($cat);
echo get_level($yourcat);
}
`
Thanks #zuzuleinen

I visited this page months back. I came back today, arrow up on the above solution then still went digging. Although it is a good solution, Wordpress often offers better or close.
get_category_parents()
This function does as Rahul has typed basically. It also calls itself which seems the most logical approach and that is why Rahul gets a point from me on this. Do not use $link, return a string of categories, explode() them then count or I suppose we could count the number of times the separator has been used and add 1.
function get_category_parents( $id, $link = false, $separator = '/', $nicename = false, $visited = array() ) {
$chain = '';
$parent = get_term( $id, 'category' );
if ( is_wp_error( $parent ) )
return $parent;
if ( $nicename )
$name = $parent->slug;
else
$name = $parent->name;
if ( $parent->parent && ( $parent->parent != $parent->term_id ) && !in_array( $parent->parent, $visited ) ) {
$visited[] = $parent->parent;
$chain .= get_category_parents( $parent->parent, $link, $separator, $nicename, $visited );
}
if ( $link )
$chain .= ''.$name.'' . $separator;
else
$chain .= $name.$separator;
return $chain;
}

Related

How to declar a variable using isset() function on Wordpress

I have a block of php codes I put in functions.php on Wordpress website, part of which is as shown below:
add_filter('request', 'my_change_term_request', 1, 1 );
function my_change_term_request($query){
$tax_name = 'ait-items'; // specify you taxonomy name here, it can be also 'category' or 'post_tag'
// Request for child terms differs, we should make an additional check
if( isset( $query['attachment'] ) && $query['attachment'] ) :
$include_children = true;
$name = $query['attachment'];
else:
$include_children = false;
if(isset($query['name'])){ $name = $query['name']; }
endif;
$term = get_term_by('slug', $name, $tax_name); // get the current term to make sure it exists
if (isset($name) && $term && !is_wp_error($term)): // check it here
if( $include_children ) {
unset($query['attachment']);
$parent = $term->parent;
while( $parent ) {
$parent_term = get_term( $parent, $tax_name);
$name = $parent_term->slug . '/' . $name;
$parent = $parent_term->parent;
}
} else {
unset($query['name']);
}
switch( $tax_name ):
case 'category':{
$query['category_name'] = $name; // for categories
break;
}
case 'post_tag':{
$query['tag'] = $name; // for post tags
break;
}
default:{
$query[$tax_name] = $name; // for another taxonomies
break;
}
endswitch;
endif;
return $query;
}
This line of codes generates error warning or notice on Wordpress:
$term = get_term_by('slug', $name, $tax_name);
like:
Notice: Undefined variable: name in /wp-content/themes/businessfinder2-child/functions.php on line 595
I have tried to replace the above line with:
$term = get_term_by('slug', if(isset($name)) { echo '$name'; }, $tax_name);
OR:
$term = get_term_by('slug', if(isset($query['name'])) { echo "$name"; }, $tax_name);
None of the above replacements work.
Very appreciate any advice.
$query is empty in nonsigular pages and it just works in singular page like post and page. Add this line in top of Function to prevent the function call in home page and etc.
if(empty($query)) return $query;
I fixed the issue. In case anyone has experience with similar issue, just declare $name as global variable before the error line like this:
global $name;
$term = get_term_by('slug', $name, $tax_name);
or at the beginning of the function.
thanks.

WordPress get template associated with category

I have created a custom template and associated it with my categories.
Now what I am trying to do is check which template is associated with a specific category.
function custom_category_template( $template ) {
$categories = get_the_category();
$category_id = $categories[0]->cat_ID;
foreach ($categories[0] as $key => $value) {
echo $key;
echo $value;
echo "</br>";
}
if ( in_category( 245 ) && !is_archive() ) {
// the idea is to get rid of the hard coded id in the if condition above and check if a particular template is associated with the category then do the below thing
$new_template = locate_template( array( 'custom.php' ) );
if ( '' != $new_template ) {
return $new_template;
}
}
return $template;
}
Is there any way to do get the template name or id or something that is attached to a particular category.
I did found this one https://codex.wordpress.org/Function_Reference/get_category_template but it doesn't help me. I am on a post and I want to retrieve the current posts category's template.

Apply the_title filter to post titles AND backend auto social-sharing plugin, but not nav menu

The Challenge
I have been trying to write a filter that applies (prepends a string) to (a) post titles of a certain post type and (b) to that same post type WordPress admin backend for use by an auto social sharing plugin.
I've gotten really close. I've achieved:
1. prepending only to custom post_type post titles
2. prepending to custom_post type titles AND all nav menu items
3. prepending to ALL titles (post, page, nav menu, and backend auto-sharing plugin)
The final, 3rd attempt got me very hopeful, but yet still, no matter the function, conditional statement, or combination I use, I can't get custom_post title AND backend social sharing plugin, but not nav menu items.
My Code - what I've tried
I've tried different conditionals, like is_admin() and !is_nav_menu with all nav menu IDs. I've also tried comparing the ID of the post to the ID of the menu. Finally, I've also tried adding the filter only to loop_start and that seems promising if combined with other statements. I will clean up my code for your review but I leave it this way for now in hopes it helps to see what I've tried and maybe where I went wrong with any of those methods.
// , $id = NULL
function append_album_review_to_title( $title ) {
global $post;
global $dont_apply_title_filter;
$text = 'Album Review: ';
$prepended_title = $text . $title;
/*
$nav_menus_obj = wp_get_nav_menus();
$nav_menu_ids = '';
foreach( $nav_menus_obj as $nav_menu ) {
$nav_menu_ids .= $nav_menu->term_id . ',';
}
rtrim($nav_menu_ids, ',');
*/
// if ( get_post_type( $post->ID ) == 'album_review' && in_the_loop() ){
// if ( get_post_type( $post->ID ) == 'album_review' && $id == get_the_ID() ){
// if ( !is_nav_menu( '32057,32058,35135,32054,32056' ) ) {
// if ( get_post_type( $post->ID ) == 'album_review' && is_nav_menu( $id ) ) {
if ( get_post_type( $post->ID ) == 'album_review' && !$dont_apply_title_filter ) {
//print_r( $nav_menu_ids );
//print_r( is_nav_menu( $nav_menu_ids ) );
return $prepended_title;
/*
} elseif ( get_post_type( $post->ID ) == 'album_review' ) {
return $title;
*/
} else {
return $title;
};
}
add_filter('the_title', 'append_album_review_to_title');
//add_action('save_post', 'custom_post_type_title', 100);
/*
function set_custom_title() {
add_filter( 'the_title', 'append_album_review_to_title', 10, 2 );
}
add_action( 'loop_start', 'set_custom_title' );
*/
Solution
function append_album_review_to_title( $title, $id = NULL ) {
if ($id) {
if ( get_post_type( $id ) == 'album_review' ){
return 'Album Review: ' . $title;
} else {
return $title;
}
} else {
return 'Album Review: ' . $title;
};
}
add_filter('the_title', 'append_album_review_to_title', 10, 2);
Explanation
First trying this:
function append_album_review_to_title( $title, $id ) {
if ( get_post_type( $id ) == 'album_review' ){
return 'Album Review: ' . $title;
} else {
return $title;
}
}
add_filter('the_title', 'append_album_review_to_title', 10, 2);
I noticed that on the backend, the social sharing plugin I am using to auto-share posts would return warnings like missing parameter 2 and Notice: Trying to get property of non-object..., and so it occurred to me that unlike the front end (nav menu and the loop), in the backend, apparently an $id is not being passed to the_title and so I can use this as a conditional.
Checking for $id will, for my purposes, tell me that if it is true, we are on front end, if it is false, then we are at backend post view.
This code accomplishes what I need (ie, modify post title in the loop, do NOT modify nav menu items, and modify the_title for use by a backend social sharing plugin):

Wordpress nextpage display Previous 2 of 10 Next

I'm using wp_link_pages() to split my post into multiple pages. I want to achieve something like this as shown in the image below. Instead of showing all the page numbers with links, I want it to show only this format (Current Page of Total Page). Please help me with the exact codes. Thank you so much in advance.
PS: I don't want to use plugins.
There is a simple solution to this problem. I've got this inspiration from source file where function wp_link_pages is defined.
function page_pagination( $echo = 1 )
{
global $page, $numpages, $multipage, $more;
if( $multipage ) { //probably you should add && $more to this condition.
$next_text = "next";
$prev_text = "prev";
if( $page < $numpages ) {
$next = _wp_link_page( $i = $page + 1 );
$next_link = $next . $next_text . "</a>";
}
if( $i = ( $page - 1 ) ) {
$prev = _wp_link_page( $i );
$prev_link = $prev . $prev_text . "</a>";
}
$output =
"<div class=\"prev-next-page\">"
. $prev_link
. "<span class=\"page-counter\">{$page} of {$numpages}</span>"
. $next_link
. "</div>";
}
if( $echo ){
echo $output;
}
return $output;
}
If you need more freedom you can always adapt this function to suit your purposes. Include function into wordpress loop! Like this for example:
if ( have_posts( ) ) {
while ( have_posts( ) ) {
the_post( );
//rest of code
the_content();
page_pagination();
}
}
As you can see, there is "private" function _wp_link_page used to solve your problem. I don't like using "private" functions, but it solves our problem.

How-to get a menu label via $post-> or $page->ID

Entirely Revised Please Reread
Hello,
The theme I am using displays the page's title as opposed to it's menu label in the breadcrumbs. I am trying to get the breadcrumbs to instead display the associated menu label if it is available and if not then default to the page_title.
I have come up with some code that I think is close. Line 4/// $menu_items = wp_get_nav_menu_items( $slug ); returns null and it should return the nav item that contains $slug of the current post. Obviously, there is something I do not understand.
What I am attempting to do is get the slug of the current post, then using the slug get the nav item post. Then extract the title of the nav item and use that in place of the page title in the breadcrumbs. If the page was not in the nav system then it should default to the page title, as might be the case for a ppc campaign landing page.
if ( is_page() && !$post->post_parent ) {
$title = null;
$slug = mpactMEDIA_get_the_slug( get_the_ID() );
$menu_items = wp_get_nav_menu_items( $slug );
//var_dump((array)$menu_items);
foreach ( (array)$menu_items as $key => $menu_item ) {
$title = $menu_item->post_title;
}
if ( $title ) { echo $delimiter . ' ' . $before . $title . $after; }
else { echo $delimiter . ' ' . $before . get_the_title() . $after; }
}
I'm my functions.php file I have the following function
function mpactMEDIA_get_the_slug( $id=null ){
if( empty($id) ) global $post;
if( empty($post) ) return '';
$id = $post->ID;
endif;
$slug = basename( get_permalink($id) );
return $slug;
}
Thank you in advance,
Tim
I read the question a few times, I got here searching for an answer, ended up making my own.
function get_menu_label_by_post_id($post_id, $menu) {
$menu_title = '';
$nav = wp_get_nav_menu_items($menu);
foreach ( $nav as $item ) {
if ( $post_id == $item->object_id ) {
$menu_title = $item->post_title;
break;
}
}
return ($menu_title !== '') ? $menu_title : get_the_title($post_id);
}
Example usage:
echo get_menu_label_by_post_id($post->ID, 'Primary Nav');
This will return what the menu label is if it finds it, otherwise just the title of the post ID.
Check the documentation for wp_get_nav_menu_items. It doesn't take a page slug as a parameter at all.
If you want to list child pages of a given page, use wp_list_pages and pass a child_of parameter to it.
Also, as a side note, if you know the $post and want the slug, it's just $post->post_name

Resources