Wp list categories


In a previous article we saw how to easily work with categories in WordPress. We covered how we can sort our posts into different categories, which can then be edited or deleted.

Having covered the basics, it’s now time to have a look at something that will be of more interest to developers: the Categories API, and how to retrieve and display category data.

Like the Links Manager API, the Categories API is a big topic, even bigger in terms of the number of functions available. In this article, we’ll be covering one function that is useful when we want to list our categories.

Listing Categories

In the Links Manager API we find an important function that allows us to list our links. It’s no surprise therefore that we find the same thing in the Categories API: wp_list_categories(), this is the function we’ll work with here.

Basically, you have to call this function in the place you want to see your categories listed.

wp_list_categories();  

WP list categories

As you can imagine, this result is entirely customizable. To mould it to our needs we can pass an argument to this function: an array containing values for the options we want to set. Let’s have a look at some of the available options.

Choosing the Categories to Display

Before seeing how to customize the output, we’ll begin with some options that allow us to choose what to display.

Include and Exclude Categories

First we find the option include which accepts a list of category IDs to display. When you use this option, wp_list_categories() will only display the categories with the IDs you passed it. You can indicate one or more IDs. If you want to indicate two or more IDs, you must separate these numbers with a comma.

$args = array(  		'include' => '15,16,9'  	);    wp_list_categories($args);

If on the other hand you don’t want to choose what to display, but rather what not to display, the exclude option is for you. It can be used exactly like include .

$args = array(  		'exclude' => '15,16,9'  	);

Note that if you want to use the exclude option, include


must be empty (its default value). Otherwise, the include option wins and only the categories passed to it will be displayed.

Another option to exclude categories is exclude_tree. Once again, it accepts a comma-separated list of categories’ IDs to exclude. The difference is that it will exclude the selected categories and all their children. Note that, to see this option working, you must set the option hierarchical to 0 (we will see below what this option does).

// 14 is the ID of "My life", parent of "My goldfish" and "My garden" which will also be hidden  $args = array(  		'exclude_tree' => '14',  		'hierarchical' => 0  	);

Ordering the Output

By default, categories are listed in alphabetical order. You can modify this behavior thanks to the orderby option, which accepts a string. You can pick from the following options: ID to order the categories by their ID (no, really?), name to sort them alphabetically (the default value), slug to sort them in the alphabetical order of their slugs, and count to order by the number of posts they contain.

The chosen order can be reversed by setting DESC (descending) as a value for the order option (by default this option is set to ASC (ascending)).

In the example below, we list the categories by the number of posts they contain: as the order is reversed, the category containing the greatest number of posts will be the first one to be displayed.

$args = array(  		'orderby' => 'count',  		'order' => 'DESC'  	);  

Limit the Number of Displayed Categories

Once we have ordered our categories, we may want to limit the number of items listed. This can be achieved using the number option. By default, this option is set to null and there is no limit so all the categories are shown. By specifying a number, you can define the maximum number of categories to display. For example, we can list the five most used categories.

$args = array(  		'orderby' => 'count',  		'order' => 'DESC',  		'number' => 5  	);

This example lists the categories with the greatest number of posts. Another solution is to hide the unused categories. To do that we can use hide_empty, a boolean set to 1 by default: empty categories are not shown. You can choose to display them by setting this to 0.

// Show me all the categories, even the empty ones  $args = array(  		'hide_empty' => 0  	);

Specifying Details to be Displayed

Details are important, and there are always some that we want to include.

Counters!

For example you may want to display the number of posts contained in each category. To display this you can use the option show_count


and set it to 1. By default, this boolean is set to 0 and this count is not shown.

$args = array(  		'show_count' => 1  	);

Note that a post in a child category will also be added to the total number of posts of its parent. For example, the screenshot below is taken with three posts in the “My life” category: while there is only one post in this category, the two others are in the child categories.

WP list categories counters

You can modify this behavior thanks to the option pad_counts. If you set this to 0, the parents’ counts will only display the number of posts in these parents’ categories and not include the posts in their child categories.

$args = array(  		'show_count' => 1,  		'pad_counts' => 0  	);

WP list categories counters parents

Descriptions of the Categories

As we saw in our previous article, we can set a description for our categories. This description can be displayed with the option use_desc_for_title


. It’s a boolean set to 1 by default: descriptions are displayed in the title attribute of the links in the list. If you don’t want to see this description you can set this to 0.

$args = array(  		'use_desc_for_title' => 1  	);

categories description

Feeds

Just as WordPress generates a feed for your posts, it also creates one for every category. Visitors can choose to only follow the updates of categories they are interested in, if they don’t like all of your content.

The links to these feeds can be shown in the list of our categories, thanks to the option feed. By default this option is set to an empty string and links are not shown. The code below shows how to enable this option.

$args = array(  		'feed' => 'RSS'  	);

categories feeds

By default, the linked feed is the RSS2 one. But WordPress can generate more feed types. If you prefer Atom for example, you can force WordPress to show this type of feed instead of the RSS2 one.

To select the type of feed you want to see displayed you can specify any of the following options : atom


, rss, rss2 and rdf.

$args = array(  		'feed' => 'Atom',  		'feed_type' => 'atom'  	);

Finally, if you prefer to use an image to link to your RSS feeds, you can indicate the URL of the image you want to see in the feed_image option. The text in the feed option will then become the alternative text for the image.

$args = array(  		'feed' => 'RSS',  		'feed_image' => 'http://website.org/my-awesome-rss-image.png'  	);

Is This Category the Current One?

If you use wp_list_categories() on an archive page (in the archive.php template), you can see that the current category (the one displayed by the archive page) is highlighted: the li tag enclosing the link to this category has one more class than the other ones, named current-cat. You don’t have to do anything to activate this behavior, and you can’t deactivate it (but you are free to not use it in your CSS!).

However, maybe it’s a behavior you want to see on more pages, like those which display a post. The good news is you can, thanks to the option current_category. This boolean is set to 0 by default. By setting it to 1 the current category will be highlighted with the previously quoted class.

$args = array(  		'current_category' => 1  	);  

For example, let’s assume that we display the list of our categories on the single.php template. Then, with the previous array, the category of the current post is highlighted thanks to the class current-cat. All we have to do now to display it is to add the appropriate CSS.

Showing the Hierarchy

If you have many categories, it’s a good idea to organise them into logical hierarchies, where we find parent categories and their children underneath them. There are a number of options for handling the display of hierarchies.

We’ll look at hierarchical first. It’s a boolean set by default to 1, whereby wp_list_categories() shows the hierarchy between the categories (with parents and children), exactly as in the screenshots since the beginning of this article. If you don’t want to show your hierarchy you can set it to 0: your categories will then be listed in one column without indenting the child categories.

Note the side effect of hierarchical: if you choose to display the hierarchy, then the parents categories will always be shown, even if they are empty and the hide_empty option is set to 1.

// Don't show me the hierarchy  $args = array(  		'hierarchical' => 0  	);  

You can also use hierarchy to do other things like displaying the children of a given category using child_of . We could describe it as the opposite of exclude_tree: we give it the ID of a category and wp_list_categories() will only display its children. However, the name of the parent category is not displayed.

// Show me all the children of this category  $args = array(  		'child_of' => 14  	);

Unlike exclude_tree, we can only pass a single ID to child_of.

The depth option allows you to control the number of levels which can be displayed in the list. It can be useful if you love categories and have a complex tree with a lot of generations. By default it is set to 0 and shows all the generations. The example below shows only two levels of categories: the parents and their first level children. If these children have their own child categories, they won’t be shown.

$args = array(  		'depth' => 2  	);

Note that depth is linked to hierarchical. In fact, if you set hierarchical to 0, giving a value to depth will be useless: all the categories will be shown, regardless of their levels in the tree. On the contrary, you can also override the value of hierarchical with depth


in one case: you set depth to -1. The effect of this value is to display all the categories without any relation. All of the categories will be shown in one column, even if hierarchical is set to 1.

Controlling the Output

By default, wp_list_categories() displays the list of our categories. If you don’t want that and prefer to store the result in a variable to display it later, you can set echo to 0.

$args = array(  		'echo' => 0  	);    $cats = wp_list_categories($args);

This can be useful if you want to modify the list before displaying it.

Next, let’s look at show_option_none. By default, if wp_list_categories() doesn’t find any category (it can happen if the other options are too restrictive for example), it displays the text “No categories“. You can change this to the text you want using this option.

$args = array(  		'show_option_none' => 'Nothing found :('  	);

Next title_li. In our tests, you may have noticed that the list of categories is encapsulated into an item of another list. This can be useful if you use wp_list_categories() in a menu for example. Moreover, WordPress displays a title for this list, which is by default “Categories“.

You can modify this default title or even disable it by playing with title_li


. It accepts a string, which is the title to display. If you give this option an empty string, the list of categories won’t be encapsulated in another list at all.

$args = array(  		'title_li' => 'My awesome categories'  	);

Be careful: if you disable the displaying of the list with an empty string you must enclose your list in ul tags!

You don’t like lists? You will love the style option: by default it is set to list and wp_list_categories() displays categories as list items. If you set style to none, your categories will be separated by br tags.

$args = array(  		'style' => 'none'  	);

Finally, you can ask WordPress to display a link to all your categories thanks to the option show_option_all. You give a string to this option, and WordPress will display a new link, pointing to all of your categories.

$args = array(  		'show_option_all' => 'All categories'  	);

Conclusion

That’s it for wp_list_categories(). The number of options available for this function is pretty big, as you can see.

Of course, the Categories API is not limited to this function. However, it is an important one: if you don’t have any specific need and just want a basic list of categories, don’t look for another function, this one is your simplest option!

Note that we didn’t talk in this article about wp_dropdown_categories(). This function displays our categories into a dropdown HTML element. Like wp_list_categories(), its output can be fully customized thanks to an array of options. These options are similar to those available with wp_list_categories() , so we won’t describe them here. The only difficulty is that some options have other default values. To learn more about wp_dropdown_categories(), you can go to the WordPress Codex.

But there are still other cases: what if we want to display our categories in a special way? In this case, wp_list_categories() is not flexible enough, as we need to build our own DOM tree. That’s why, in the next article, we’ll have a look at some other useful functions in the Categories API.

www.sitepoint.com

К счастью нашел документацию, как выводятся категории в этом движке. Для вывода всех категорий, куда угодно вставьте код: <?php wp_list_categories( $args ); ?>

Важно! В этой статье есть более продвинутый способ реализации данного решения.

Если так сделать, то выведутся все не пустые категории с дочерним списком. Итак, освящу только самые главные параметры этой функции, которые могут пригодиться, а потом объясню, как их использовать, чтобы вывести списком определенные категории в wordpress.

‘orderby’ => ‘name’,     — Сортировка списка по следующим критериям:
ID — сортировка по ID;
name — сортировка по названию (по умолчанию);
slug — сортировка по алфавиту;
count — по количеству записей в категории;

‘show_count’ => 0,     — Показывать (1) или нет (0) количество записей в категории. По умолчанию — нет.

‘hide_empty’ => 1, — Показывать (0) или нет (1) пустые категории. По умолчанию: нет

‘child_of’ => 0, — Показать дочерние категории. В параметре указывается ID родительской категории. По умолчанию: 0

‘exclude’ => ‘ ‘, — Исключить категории из списка. Нужно указывать ID категорий через запятую. Если этот параметр указан, параметр child_of будет отменен. По умолчанию: ‘ ‘

‘include’ => ‘ ‘, — Вывести списком только указанные категории. Указывать нужно ID категорий через запятую. По умолчанию: ‘ ‘

‘title_li’ => __( ‘Categories’ ), — Название всего списка, у меня выводилось Рубрики, я поменял на категории — вот так: ‘title_li’ => ‘Категории’,

 

Есть еще множество других параметров, но мне нужны только эти. Итак, чтобы вывести все дочерние категории одной определенной категории я должен задать параметры и вызывать функцию:

<?php $args = array(
‘title_li’ => ‘Программирование’,
‘child_of’ => 6,
‘hide_empty’ => 0,
‘show_count’ => 1);
wp_list_categories( $args ); ?>

В этом случае выведется список нужных мне подкатегорий. Как все это использовать? В моем шаблоне файл post-excerpt.php отвечает за вывод категорий. Практически в самый вверх кода вставляю

<?php
if ($_SERVER[‘REQUEST_URI’] == «/category/programmirovan/»)
{$args = array(
‘title_li’ => ‘Программирование’,
‘child_of’ => 6,
‘hide_empty’ => 0,
‘show_count’ => 1);
wp_list_categories( $args ); }
?>

где /category/programmirovan/ настроена на ссылку моей категории. То есть, если человек зайдет только по этой ссылке, то ему покажутся все категории, которые я захотел отобразить. :)

Пример:

Untitled-1

blogprogram.ru

function wp_list_categories( $args = '' ) { 	$defaults = array( 		'child_of' => 0, 		'current_category' => 0, 		'depth' => 0, 		'echo' => 1, 		'exclude' => '', 		'exclude_tree' => '', 		'feed' => '', 		'feed_image' => '', 		'feed_type' => '', 		'hide_empty' => 1, 		'hide_title_if_empty' => false, 		'hierarchical' => true, 		'order' => 'ASC', 		'orderby' => 'name', 		'separator' => '<br />', 		'show_count' => 0, 		'show_option_all' => '', 		'show_option_none' => __( 'No categories' ), 		'style' => 'list', 		'taxonomy' => 'category', 		'title_li' => __( 'Categories' ), 		'use_desc_for_title' => 1, 	);  	$r = wp_parse_args( $args, $defaults );  	if ( !isset( $r['pad_counts'] ) && $r['show_count'] && $r['hierarchical'] ) 		$r['pad_counts'] = true;  	// Descendants of exclusions should be excluded too. 	if ( true == $r['hierarchical'] ) { 		$exclude_tree = array();  		if ( $r['exclude_tree'] ) { 			$exclude_tree = array_merge( $exclude_tree, wp_parse_id_list( $r['exclude_tree'] ) ); 		}  		if ( $r['exclude'] ) { 			$exclude_tree = array_merge( $exclude_tree, wp_parse_id_list( $r['exclude'] ) ); 		}  		$r['exclude_tree'] = $exclude_tree; 		$r['exclude'] = ''; 	}  	if ( ! isset( $r['class'] ) ) 		$r['class'] = ( 'category' == $r['taxonomy'] ) ? 'categories' : $r['taxonomy'];  	if ( ! taxonomy_exists( $r['taxonomy'] ) ) { 		return false; 	}  	$show_option_all = $r['show_option_all']; 	$show_option_none = $r['show_option_none'];  	$categories = get_categories( $r );  	$output = ''; 	if ( $r['title_li'] && 'list' == $r['style'] && ( ! empty( $categories ) || ! $r['hide_title_if_empty'] ) ) { 		$output = '<li class="' . esc_attr( $r['class'] ) . '">' . $r['title_li'] . '<ul>'; 	} 	if ( empty( $categories ) ) { 		if ( ! empty( $show_option_none ) ) { 			if ( 'list' == $r['style'] ) { 				$output .= '<li class="cat-item-none">' . $show_option_none . '</li>'; 			} else { 				$output .= $show_option_none; 			} 		} 	} else { 		if ( ! empty( $show_option_all ) ) {  			$posts_page = '';  			// For taxonomies that belong only to custom post types, point to a valid archive. 			$taxonomy_object = get_taxonomy( $r['taxonomy'] ); 			if ( ! in_array( 'post', $taxonomy_object->object_type ) && ! in_array( 'page', $taxonomy_object->object_type ) ) { 				foreach ( $taxonomy_object->object_type as $object_type ) { 					$_object_type = get_post_type_object( $object_type );  					// Grab the first one. 					if ( ! empty( $_object_type->has_archive ) ) { 						$posts_page = get_post_type_archive_link( $object_type ); 						break; 					} 				} 			}  			// Fallback for the 'All' link is the posts page. 			if ( ! $posts_page ) { 				if ( 'page' == get_option( 'show_on_front' ) && get_option( 'page_for_posts' ) ) { 					$posts_page = get_permalink( get_option( 'page_for_posts' ) ); 				} else { 					$posts_page = home_url( '/' ); 				} 			}  			$posts_page = esc_url( $posts_page ); 			if ( 'list' == $r['style'] ) { 				$output .= "<li class='cat-item-all'><a href='$posts_page'>$show_option_all</a></li>"; 			} else { 				$output .= "<a href='$posts_page'>$show_option_all</a>"; 			} 		}  		if ( empty( $r['current_category'] ) && ( is_category() || is_tax() || is_tag() ) ) { 			$current_term_object = get_queried_object(); 			if ( $current_term_object && $r['taxonomy'] === $current_term_object->taxonomy ) { 				$r['current_category'] = get_queried_object_id(); 			} 		}  		if ( $r['hierarchical'] ) { 			$depth = $r['depth']; 		} else { 			$depth = -1; // Flat. 		} 		$output .= walk_category_tree( $categories, $depth, $r ); 	}  	if ( $r['title_li'] && 'list' == $r['style'] && ( ! empty( $categories ) || ! $r['hide_title_if_empty'] ) ) { 		$output .= '</ul></li>'; 	}  	/** 	 * Filters the HTML output of a taxonomy list. 	 * 	 * @since 2.1.0 	 * 	 * @param string $output HTML output. 	 * @param array $args An array of taxonomy-listing arguments. 	 */ 	$html = apply_filters( 'wp_list_categories', $output, $args );  	if ( $r['echo'] ) { 		echo $html; 	} else { 		return $html; 	} } 

developer.wordpress.org

Wp list categoriesДля того, чтобы вывести список категорий, или какой-либо другой список терминов таксономии, в wordpress есть функция wp_list_categories(). Эта функция подходит для того, чтобы например  создать выпадающее меню категорий в WordPress. Важно, что с помощью этой функции можно выводить не только список категорий, но и любой список терминов таксономии, например список тэгов, для этого в качестве значения параметра «taxonomy» нужно указать «post_tag».

Рассмотрим все параметры функции wp_list_categories():

child_of — В значении этого параметра можно указать Id категории, если вы хотите вывести подкатегории только этой категории. По умолчанию значение 0 (все категории и подкатегории).

current_category — id категории, или массив из id категорий, к которым будет добавлен класс «current-cat» (класс текущей категории).

depth — уровень вложенности для категорий. Например значение 1 означает, что будет выводится только список категорий 1-го уровня вложенности, т. е. категории без подкатегорий, значение 2 означает, что будет выводиться категории с подкатегориями 1-го уровня и т. д. (По умолчанию выводятся подкатегории всех уровней вложенности)

echo — если значение параметра равно «0», то функция будет возвращать полученный список в виде переменной, если «1», то просто выводить его через оператор echo.

exclude — параметр для удаления категорий из списка. Значение параметра — строка из id категорий для удаления, перечисленных через запятые (прим. «2,4,5»).

exclude_tree —  параметр для удаления категорий из списка вместе с подкатегориями. Значение параметра — строка из id категорий, перечисленных через запятые (прим. «2,4,5»).

feed — добавляет к каждой категории ссылку на ее RSS ленту. В качестве значения  параметра передается текст (анкор) ссылки.

feed_image — добавляет к каждой категории ссылку на ее RSS ленту, только вместо названия ссылки будет отображаться ее картинка. Значение параметра — URL адрес картинки для RSS ленты.

feed_type — тип RSS-ленты (atom, rdf, rss, rss2 (по умолчанию))

hide_empty — скрывать категории, в которых нет записей (1 — скрывать, 0 — выводить, по умолчанию скрывать)

hide_title_if_empty — скрывать заголовок списка если список пуст (true — скрывать, false — вывести)

hierarchical — создавать список с учетом иерархии (подкатегории формируются в виде вложенных списков), true — да, false — нет

order — порядок сортировки категорий. «ASC» — сортировка элементов в прямом порядке (по-умолчанию), «DESC» — сортировка категорий в обратном порядке.

orderby — поле, по которому будет производиться сортировка элементов списка. Сортировка может быть по имени (значение «name»),  id записи («ID»), по slug (значение «slug»), и по количеству записей категории (значение «count»).

separator — разделитель элементов списка. По умолчанию ‘<br />’.

show_option_all — добавляет элемент списка категорий, который будет указывать на главную страницу сайта (страницу со всеми записями). Значение параметра — название элемента. По умолчанию отсутствует.

show_option_none — Текст, который будет показан при отсутствии категорий в списке. По умолчанию __( ‘No categories’ ).

show_count — показывать количество записей у каждой категории (0 — не показывать, 1 — показывать).

style — Тип списка для категорий. Тут всего 2 значения: «list» — элементы выводятся в виде html списка ul, либо «none» — элементы выводятся в виде ссылок <a>.

taxonomy — id таксономии, элементы которой будут выведены функцией wp_list_categories(). Для того чтобы вывести с помощью этой функции список тэгов например, у этого параметра нужно указать значение «post_tag».

title_li — Заголовок списка. По умолчанию выводит __( ‘Categories’ ) — что в переводе означает «Рубрики». Чтобы заголовок не отображался, укажите значение «».

use_desc_for_title — вставляет атрибут title у ссылок. 1 — вставлять, 0 — нет. По умолчанию 1.

Теперь посмотрим как это работает на практике:

Вывод всех подкатегорий категории с ID = 10 и с заголовком «Администрирование UNIX».

$args = array(   'child_of' => 10,   'title_li' => 'Администрирование UNIX',   );     wp_list_categories( $args );

Вывод всех категорий без подкатегорий с сортировкой по имени

$args = array(   'depth' => 1,   'orderby' => 'name',   );     wp_list_categories($args);

Вывод всех категорий, кроме категорий с id 4, 5 и 34, с сортировкой по имени и без учета иерархии:

$args = array(   'exclude' => '4,5,34',   'orderby' => 'name',   'hierarchical' => false,   );     wp_list_categories($args);

Вывод всех категорий с указанием количества записей у каждой категории, отображением пустых категорий и с сортировкой по имени в обратном порядке:

$args = array(   'show_count' => 1,   'order' => 'DESC',   'orderby' => 'name',   'hide_empty' => 0,   );     wp_list_categories($args);

Вывод списка тэгов, т. е. всех терминов таксономии с названием post_tag с сортировкой по имени:

$args = array(   'taxonomy' => 'post_tag',   'orderby' => 'name',   );     wp_list_categories($args);

webistore.ru

Вывод дочерних категорий в wordpress

Вставляем данный код в то место, где хотим выводить подкатегории (дочерние категории в WordPress). Это может быть: header, sidebar, или же footer вашего сайта.

 <?php $category = get_the_category(); if (is_category()) {  $this_category = get_category($cat);  if($this_category->category_parent) {  $this_category = wp_list_categories(  array(  'orderby' => 'name',  'show_count' => '0',  'current_category' => ''.$category[0]->cat_ID.'',  'title_li' => '',  'use_desc_for_title' => '0',  'child_of' => ''.$this_category->category_parent.'',  'echo' => '0',  'walker' => new Subcategory_Walker_Category  )  );  } else {  $this_category = wp_list_categories(  array(  'orderby' => 'name',  'depth' => '1',  'show_count' => '0',  'current_category' => ''.$category[0]->cat_ID.'',  'title_li' => '',  'use_desc_for_title' => '0',  'child_of' => ''.$this_category->cat_ID.'',  'echo' => '0',  'walker' => new Subcategory_Walker_Category  )  );  } } elseif ( is_single()) {  if($category[0]->category_parent) {  $this_category = wp_list_categories(  array(  'orderby' => 'name',  'show_count' => '0',  'current_category' => ''.$category[0]->cat_ID.'',  'title_li' => '',  'use_desc_for_title' => '0',  'child_of' => ''.$category[0]->category_parent.'',  'echo' => '0',  'walker' => new Subcategory_Walker_Category  )  );  } else {  $this_category = wp_list_categories(  array(  'orderby' => 'name',  'show_count' => '0',  'current_category' => ''.$category[0]->cat_ID.'',  'title_li' => '',  'use_desc_for_title' => '0',  'child_of' => ''.$category[0]->cat_ID.'',  'echo' => '0',  'walker' => new Subcategory_Walker_Category  )  );  } } ?> <?php if(is_category() || is_single()) { ?> <!-- Показываем наши подкатегории сугубо в категориях и записях -->  <div>  <div>  <?php  foreach((get_the_category()) as $childcat) {  $parentcat = $childcat->category_parent;  echo get_cat_name($parentcat); //Вывод названия родительской категории, если есть такая необходимость  }  ?>  </div>  <ul>  <?php echo $this_category; //Вывод подкатегорий ?>  </ul>  </div> <?php } ?> 

Класс Walker для wp_list_categories

Класс Walker для wp_list_categories используется для построения меню, стилизации, добавления своих классов в список категорий. Вставляем данный код в файлик functions.php:

 class Subcategory_Walker_Category extends Walker_Category {  function start_el( &$output, $category, $depth = 0, $args = array(), $id = 0 ) {  extract($args);  $cat_name = esc_attr( $category->name );  $cat_name = apply_filters( 'list_cats', $cat_name, $category );  $link = '<a href="' . esc_url( get_term_link($category) ) . '" ';  if ( $use_desc_for_title == 0 || empty($category->description) )  $link .= 'title="' . esc_attr( sprintf(__( 'View all posts filed under %s' ), $cat_name) ) . '"';  else  $link .= 'title="' . esc_attr( strip_tags( apply_filters( 'category_description', $category->description, $category ) ) ) . '"';  $link .= '>';  $link .= $cat_name . '</a>';  if ( !empty($feed_image) || !empty($feed) ) {  $link .= ' ';  if ( empty($feed_image) )  $link .= '(';  $link .= '<a href="' . esc_url( get_term_feed_link( $category->term_id, $category->taxonomy, $feed_type ) ) . '"';  if ( empty($feed) ) {  $alt = ' alt="' . sprintf(__( 'Feed for all posts filed under %s' ), $cat_name ) . '"';  } else {  $title = ' title="' . $feed . '"';  $alt = ' alt="' . $feed . '"';  $name = $feed;  $link .= $title;  }  $link .= '>';  if ( empty($feed_image) )  $link .= $name;  else  $link .= "<img src='$feed_image'$alt$title" . ' />';  $link .= '</a>';  if ( empty($feed_image) )  $link .= ')';  }  if ( !empty($show_count) )  $link .= ' (' . intval($category->count) . ')';  if ( 'list' == $args['style'] ) {  $output .= "t<li";  $class = 'cat-item';  // Your custom class  if ($depth)  $class .= '';  if ( !empty($current_category) ) {  $_current_category = get_term( $current_category, $category->taxonomy );  if ( $category->term_id == $current_category )  $class .= ' current-cat';  elseif ( $category->term_id == $_current_category->parent )  $class .= ' current-cat-parent';  }  $output .= ' class="' . $class . '"';  $output .= ">$linkn";  } else {  $output .= "t$link<br />n";  }  } } 

Вот в принципе и все, теперь перемещение по рубрикам и подрубрикам сайта, осуществляется всего в одно или два щелчка мышкой. При этом у вас всегда есть возможность быстрого перемещения по дочерним категориям находясь в их родительской категории или записях.

Делайте навигацию предельно понятно и удобно для своих посетителей. Даже если реализация довольно сложная и муторная.

Все вопросы, предложения и просьбы, пишите в комментариях к статье. 🙂

evgmoskalenko.com

Пример:

Вот как это будет выглядеть в итоге:

misha.blog

  • 2825
  • 0
  • Рубрика: WordPress

Доброго времени суток!
Сегодня мы рассмотрим функцию wp_list_categories(), с помощью которой можно вывести список рубрик, например в сайдбаре и настроить вывод как нам угодно. Можно исключить рубрики, указать метод сортировки и тд.
Вот пример списка с моего сайта.

   <ul>  	 <?php wp_list_categories('exclude=10&title_li='); ?>   </ul>  


exclude=10
— отключение вывода рубрики с ID 10
title_li= пустой параметр, чтобы избавиться от заголовка(РУБРИКИ). Я его прописал немного иначе.
Результат в html будет выглядеть примерно так:

  <ul>   <li class="cat-item cat-item-14">   <a title="Просмотреть все записи в рубрике «Новости»" href=""></a>   </li>   <li class="cat-item cat-item-11 current-cat">   <a title="Просмотреть все записи в рубрике «Статьи»" href=""></a>   </li>  </ul>  

для более тонкой настройки данной функции, у нее есть еще некоторые параметры, которые мы рассмотрим.

show_option_all
(строка) Нужно ли добавить ссылку на главную страницу? Можно указать любое значение, например ‘На главную’.

orderby
(строка) Каким образом вы хотите отсортировать категории?

  • ID – по id категории (по умолчанию)
  • name – по имени
  • slug – по ярлыку
  • count – по числу записей

order
(строка) Устанавливает порядок сортировки.

  • asc – по возрастанию (по умолчанию)
  • desc – по убыванию

style
(строка) Стиль вывода списка категорий.

  • list – в виде
  • -списка (по умолчанию)
  • none – в виде ссылок, разделенных тегом

show_count
(логическое) Указывает в скобках количество постов в каждой из рубрик.

  • 1 – да
  • 0 – нет (по умолчанию)

hide_empty
(логическое) Нужно ли исключить пустые рубрики (категории) из списка?

  • 1 – да (по умолчанию)
  • 0 – нет

use_desc_for_title
(логическое) Нужно ли использовать описание рубрик в атрибуте title для ссылок, если оно имеется.

  • 1 – да (по умолчанию)
  • 0 – нет

child_of
(целое число) Нужно указать id рубрики, подрубрики которой вы хотите вывести.

feed
(строка) Рядом с каждой категорией вставляет ссылку на RSS-ленту. Указанное значение будет текстом этих ссылок.

feed_image
(строка) Аналогичен предыдущему параметру, но только вставляет ссылку с картинкой. В качестве значения укажите адрес картинки.

feed_type
(строка) Тип RSS-ленты.

  • atom
  • rdf
  • rss
  • rss2 (по умолчанию)

exclude
(целое число) Перечислите через запятую id категорий, которые вы хотите исключить из списка.

exclude_tree
(целое число) Исключить рубрику и все её подрубрики из списка. Работает только при выключенном hierarchical.

include
(целое число) Укажите через запятую категории (их id), которые вы хотите включить в список.
hierarchical
(логическое) Нужно ли создавать вложенные списки для подкатегорий?

  • 1 – да (по умолчанию)
  • 0 – нет

pad_counts
(логический) Считать общее количество постов во вложенных категориях и показывать это число рядом с родительской категорией. Параметр включается автоматически при включенных show_counts и hierarchical. Добавлен с версии 2.9.
По умолчанию: 0 (false)
title_li
(строка) Заголовок для списка категорий. По умолчанию __( ‘Categories’ ). То есть в русском WordPress это будет переведено в «Рубрики». Оставьте параметр пустым, чтобы избавиться от заголовка.

number

(целое число) Сколько категорий нужно отобразить в списке?

echo

(логическое) Вывод списка категорий или сохранение результата в переменную.

  • 1 – да (по умолчанию)
  • 0 – нет

depth
(целое число) Количество уровней вложенности списка.

  • 0 – неограниченно (по умолчанию)
  • -1 – без уровней вложенности, параметр hierarchical игнорируется
  • n – любое целое число

taxonomy
(строка) Выберите таксономию для вывода

  • category – рубрики (по умолчанию)
  • taxonomy – любая зарегистрированная таксономия

current_category
(целое число) Укажите id категории из списка, для которой вы хотите добавить css-класс «current-cat». По умолчанию он добавляется к той категории, в которой в данный момент находится пользователь.

Есть еще один момент. Если вы много пропишите свойств, то в будущем просто запутаетесь где и что. Поэтому сначала функции можно присвоить массив $args, после чего он просто указывается в скобках. Вот как пример:

  <?php  $args = array(   'orderby' => 'name', // сортируем по названиям   'show_count' => 0, // не показываем количество записей   'pad_counts' => 0, // не показываем количество записей у родителей   'hierarchical' => 1, // древовидное представление   'title_li' => '' // список без заголовка  );  ?>    <ul>  <?php wp_list_categories( $args ); ?>  </ul>  

На этом все. Спасибо за внимание ?

gnatkovsky.com.ua

jQuery solution:

You could try this if you want to use jQuery:

<script> jQuery(document).ready(function($) {  $('li.cat-item:has(ul.children)').addClass('i-have-kids'); });  </script> 

to add the class i-have-kids to all the li parents that include the items ul.children, within the HTML generated from wp_list_categories().

Category walker solution:

You could take a look at the Walker_Category class in /wp-includes/category-template.php and extend it with an extra part like:

$termchildren = get_term_children( $category->term_id, $category->taxonomy ); if(count($termchildren)>0){  $class .= ' i-have-kids'; } 

If we skip the feed image and feed parts, the extended walker could look like this:

class Walker_Category_Find_Parents extends Walker_Category {  function start_el( &$output, $category, $depth = 0, $args = array(), $id = 0 ) {  extract($args);   $cat_name = esc_attr( $category->name );  $cat_name = apply_filters( 'list_cats', $cat_name, $category );  $link = '<a href="' . esc_url( get_term_link($category) ) . '" ';  if ( $use_desc_for_title == 0 || empty($category->description) )  $link .= 'title="' . esc_attr( sprintf(__( 'View all posts filed under %s' ), $cat_name) ) . '"';  else  $link .= 'title="' . esc_attr( strip_tags( apply_filters( 'category_description', $category->description, $category ) ) ) . '"';  $link .= '>';  $link .= $cat_name . '</a>';   if ( !empty($show_count) )  $link .= ' (' . intval($category->count) . ')';   if ( 'list' == $args['style'] ) {  $output .= "t<li";  $class = 'cat-item cat-item-' . $category->term_id;   $termchildren = get_term_children( $category->term_id, $category->taxonomy );  if(count($termchildren)>0){  $class .= ' i-have-kids';  }   if ( !empty($current_category) ) {  $_current_category = get_term( $current_category, $category->taxonomy );  if ( $category->term_id == $current_category )  $class .= ' current-cat';  elseif ( $category->term_id == $_current_category->parent )  $class .= ' current-cat-parent';  }  $output .= ' class="' . $class . '"';  $output .= ">$linkn";  } else {  $output .= "t$link<br />n";  }  }  } 

You could further take out the parts that you don’t need.

Usage example:

<?php  $args = array(  'taxonomy' => 'my_custom_taxonomy_slug',  'orderby' => 'name',  'hide_empty' => 0,  'title_li' => '',  'hierarchical' => 1,  'walker' => new Walker_Category_Find_Parents(), ); ?> <ul class="menu">  <?php wp_list_categories( $args ); ?> </ul> 

Output example:

Here’s a list example, using the Walker_Category_Find_Parents walker:

List example

with the following HTML structure:

<ul class="menu">  <li class="cat-item cat-item-1">  <a href="http://example.com/category/plants/">plants</a>  </li>  <li class="cat-item cat-item-2 i-have-kids">  <a href="http://example.com/category/animals/">animals</a>  <ul class="children">  <li class="cat-item cat-item-3 i-have-kids">  <a href="http://example.com/category/animals/birds/">birds</a>  <ul class="children">  <li class="cat-item cat-item-4">  <a href="http://example.com/category/animals/birds/falcons/">falcons</a>  </li>  </ul>  </li>  </ul>  </li>  <li class="cat-item cat-item-5">  <a href="http://example.com/category/stones">stones</a>  </li> </ul> 

I just removed the title attributes to make it more readable.

But you can see where the i-have-kids class is added to the li tags with children.

When I visit the / Animals / Birds / category, the HTML structure becomes:

<ul class="menu">  <li class="cat-item cat-item-1">  <a href="http://example.com/category/plants/">plants</a>  </li>  <li class="cat-item cat-item-2 i-have-kids current-cat-parent">  <a href="http://example.com/category/animals/">animals</a>  <ul class="children">  <li class="cat-item cat-item-3 i-have-kids current-cat">  <a href="http://example.com/category/animals/birds/">birds</a>  <ul class="children">  <li class="cat-item cat-item-4">  <a href="http://example.com/category/animals/birds/falcons/">falcons</a>  </li>  </ul>  </li>  </ul>  </li>  <li class="cat-item cat-item-5">  <a href="http://example.com/category/stones">stones</a>  </li> </ul> 

wordpress.stackexchange.com


You May Also Like

About the Author: admind

Добавить комментарий

Ваш e-mail не будет опубликован. Обязательные поля помечены *

Этот сайт использует Akismet для борьбы со спамом. Узнайте, как обрабатываются ваши данные комментариев.