Чтобы создать хлебные крошки WordPress можно использовать какой-нибудь плагин, но если вы боретесь за скорость загрузки сайта и не хотите его загромождать, или настройки плагина не отвечают вашим требованиям, вставьте в файл functions.php приведённый код:
// Breadcrumbs
function custom_breadcrumbs() {
// Настройки
$separator = ' / ';
$breadcrums_id = 'breadcrumbs';
$breadcrums_class = 'breadcrumbs';
$home_title = 'Главная';
// Если есть категории пользовательского типа постов введи его name (например portfolio_tags)
$custom_taxonomy = 'portfolio_tags';
// вызов цикла
global $post,$wp_query;
// не показываем на главной
if ( !is_front_page() ) {
// Создаём хлебные крошки
echo '<ul id="' . $breadcrums_id . '" class="' . $breadcrums_class . '">';
// Главная страница в крошках
echo '<li class="item-home"><a class="c-yellow bread-home" href="' . get_home_url() . '" title="' . $home_title . '">' . $home_title . '</a></li>';
echo '<li class="separator separator-home"> ' . $separator . ' </li>';
if ( (bool) $wp_query->is_posts_page ) {
$shortTitle = get_the_title( get_option('page_for_posts', true));
$field = get_field('breadcrumbs_title', get_option('page_for_posts'));
if (!empty($field)){
$shortTitle = $field;
}
echo '<li class="item-current item-archive"><span class="bread-current bread-archive">' . $shortTitle . '</span></li>';
} else if ( is_archive() && is_tax() && is_front_page() && !is_category() && !is_tag() ) {
// Для кастомных типов постов
$post_type = get_post_type();
// If it is a custom post type display name and link
if($post_type != 'post') {
$post_type_object = get_post_type_object($post_type);
$post_type_archive = get_post_type_archive_link($post_type);
$home_url = get_home_url('/');
echo '<li class="item-cat item-custom-post-type-' . $post_type . '"><a class="bread-cat bread-custom-post-type-' . $post_type . '" href="' . $home_url .'/'. $post_type . '" title="' . $post_type_object->labels->name . '">' . $post_type_object->labels->name . '</a></li>';
echo '<li class="separator"> ' . $separator . ' </li>';
}
$custom_tax_name = get_queried_object()->name;
echo '<li class="item-current item-archive"><span class="bread-current bread-archive">' . $custom_tax_name . '</span></li>';
} else if ( is_single() ) {
// если сингл поста кастомного типа
$post_type = get_post_type();
// If it is a custom post type display name and link
if($post_type != 'post') {
$post_type_object = get_post_type_object($post_type);
$post_type_archive = get_post_type_archive_link($post_type);
$home_url = get_home_url('/');
echo '<li class="item-cat item-custom-post-type-' . $post_type . '"><a class="bread-cat bread-custom-post-type-' . $post_type . '" href="' . $home_url .'/'. $post_type . '" title="' . $post_type_object->labels->name . '">' . $post_type_object->labels->name . '</a></li>';
echo '<li class="separator"> ' . $separator . ' </li>';
}
// Получаем категории записи
$category = get_the_category();
if(!empty($category)) {
// получаем посленюю из категорий записи
$last_category = end(array_values($category));
// Получаем родительскую категорию
$get_cat_parents = rtrim(get_category_parents($last_category->term_id, true, ','),',');
$cat_parents = explode(',',$get_cat_parents);
// Цикл родительских категорий и сохранение в переменную $cat_display
$cat_display = '';
foreach($cat_parents as $parents) {
$cat_display .= '<li class="item-cat">'.$parents.'</li>';
$cat_display .= '<li class="separator"> ' . $separator . ' </li>';
}
}
// Если кастомный тип постов с кастомной таксономией
$taxonomy_exists = taxonomy_exists($custom_taxonomy);
if(empty($last_category) && !empty($custom_taxonomy) && $taxonomy_exists) {
$taxonomy_terms = get_the_terms( $post->ID, $custom_taxonomy );
$cat_id = $taxonomy_terms[0]->term_id;
$cat_nicename = $taxonomy_terms[0]->slug;
$cat_link = get_term_link($taxonomy_terms[0]->term_id, $custom_taxonomy);
$cat_name = $taxonomy_terms[0]->name;
}
// Check if the post is in a category
if(!empty($last_category)) {
echo $cat_display;
echo '<li class="item-current item-' . $post->ID . '"><span class="bread-current bread-' . $post->ID . '" title="' . get_the_title() . '">' . get_the_title() . '</span></li>';
// Else if post is in a custom taxonomy
} else if(!empty($cat_id)) {
echo '<li class="item-cat item-cat-' . $cat_id . ' item-cat-' . $cat_nicename . '"><a class="bread-cat bread-cat-' . $cat_id . ' bread-cat-' . $cat_nicename . '" href="' . $cat_link . '" title="' . $cat_name . '">' . $cat_name . '</a></li>';
echo '<li class="separator"> ' . $separator . ' </li>';
echo '<li class="item-current item-' . $post->ID . '"><span class="bread-current bread-' . $post->ID . '" title="' . get_the_title() . '">' . get_the_title() . '</span></li>';
} else {
echo '<li class="item-current item-' . $post->ID . '"><span class="bread-current bread-' . $post->ID . '" title="' . get_the_title() . '">' . get_the_title() . '</span></li>';
}
} else if ( is_category() ) {
// Category page
echo '<li class="item-current item-cat"><span class="bread-current bread-cat">' . single_cat_title('', false) . '</span></li>';
} else if ( is_page() ) {
// Standard page
if( $post->post_parent ){
// If child page, get parents
$anc = get_post_ancestors( $post->ID );
// Get parents in the right order
$anc = array_reverse($anc);
// Parent page loop
if ( !isset( $parents ) ) $parents = null;
foreach ( $anc as $ancestor ) {
$parents .= '<li class="item-parent item-parent-' . $ancestor . '"><a class="bread-parent bread-parent-' . $ancestor . '" href="' . get_permalink($ancestor) . '" title="' . get_the_title($ancestor) . '">' . get_the_title($ancestor) . '</a></li>';
$parents .= '<li class="separator separator-' . $ancestor . '"> ' . $separator . ' </li>';
}
// Показываем родительскую страницу
echo $parents;
// Текущая страница
$shortTitle = get_the_title();
$field = get_field('breadcrumbs_title', $post->ID);
if (!empty($field)){
$shortTitle = $field;
}
echo '<li class="item-current item-' . $post->ID . '"><span title="' . get_the_title() . '"> ' . $shortTitle . '</span></li>';
} else {
$shortTitle = get_the_title();
$field = get_field('breadcrumbs_title', $post->ID);
if (!empty($field)){
$shortTitle = $field;
}
// Just display current page if not parents
echo '<li class="item-current item-' . $post->ID . '"><span class="bread-current bread-' . $post->ID . '"> ' . $shortTitle . '</span></li>';
}
} else if ( is_tag() ) {
// страница тэгов
// Информация о теге
$term_id = get_query_var('tag_id');
$taxonomy = 'post_tag';
$args = 'include=' . $term_id;
$terms = get_terms( $taxonomy, $args );
$get_term_id = $terms[0]->term_id;
$get_term_slug = $terms[0]->slug;
$get_term_name = $terms[0]->name;
// Показать имя тега
echo '<li class="item-current item-tag-' . $get_term_id . ' item-tag-' . $get_term_slug . '"><span class="bread-current bread-tag-' . $get_term_id . ' bread-tag-' . $get_term_slug . '">' . $get_term_name . '</span></li>';
} elseif ( is_day() ) {
// архивы по дням
// Ссылка на архив за год
echo '<li class="item-year item-year-' . get_the_time('Y') . '"><a class="bread-year bread-year-' . get_the_time('Y') . '" href="' . get_year_link( get_the_time('Y') ) . '" title="' . get_the_time('Y') . '">' . get_the_time('Y') . ' Archives</a></li>';
echo '<li class="separator separator-' . get_the_time('Y') . '"> ' . $separator . ' </li>';
// Ссылка на архив за месяц
echo '<li class="item-month item-month-' . get_the_time('m') . '"><a class="bread-month bread-month-' . get_the_time('m') . '" href="' . get_month_link( get_the_time('Y'), get_the_time('m') ) . '" title="' . get_the_time('M') . '">' . get_the_time('M') . ' Archives</a></li>';
echo '<li class="separator separator-' . get_the_time('m') . '"> ' . $separator . ' </li>';
// Показать день
echo '<li class="item-current item-' . get_the_time('j') . '"><span class="bread-current bread-' . get_the_time('j') . '"> ' . get_the_time('jS') . ' ' . get_the_time('M') . ' Archives</span></li>';
} else if ( is_month() ) {
// Архив за месяц
echo '<li class="item-year item-year-' . get_the_time('Y') . '"><a class="bread-year bread-year-' . get_the_time('Y') . '" href="' . get_year_link( get_the_time('Y') ) . '" title="' . get_the_time('Y') . '">' . get_the_time('Y') . ' Archives</a></li>';
echo '<li class="separator separator-' . get_the_time('Y') . '"> ' . $separator . ' </li>';
// показываем месяц
echo '<li class="item-month item-month-' . get_the_time('m') . '"><span class="bread-month bread-month-' . get_the_time('m') . '" title="' . get_the_time('M') . '">' . get_the_time('M') . ' Archives</span></li>';
} else if ( is_year() ) {
echo '<li class="item-current item-current-' . get_the_time('Y') . '"><span class="bread-current bread-current-' . get_the_time('Y') . '" title="' . get_the_time('Y') . '">' . get_the_time('Y') . ' Archives</span></li>';
} else if ( is_author() ) {
// Архив автора
// Информация об авторе
global $author;
$userdata = get_userdata( $author );
// Имя автора
echo '<li class="item-current item-current-' . $userdata->user_nicename . '"><span class="bread-current bread-current-' . $userdata->user_nicename . '" title="' . $userdata->display_name . '">' . 'Автор: ' . $userdata->display_name . '</span></li>';
} else if ( get_query_var('paged') ) {
// Постраничные архивы
echo '<li class="item-current item-current-' . get_query_var('paged') . '"><span class="bread-current bread-current-' . get_query_var('paged') . '" title="Page ' . get_query_var('paged') . '">'.__('Страница') . ' ' . get_query_var('paged') . '</span></li>';
} else if ( is_search() ) {
// Страница результатов поиска
echo '<li class="item-current item-current-' . get_search_query() . '"><span class="bread-current bread-current-' . get_search_query() . '" title="Search results for: ' . get_search_query() . '">Результат поиска для: ' . get_search_query() . '</span></li>';
} elseif ( is_404() ) {
// 404 страница
echo '<li>' . 'Error 404' . '</li>';
}
echo '</ul>';
}
}
В строке 127 записана ситуация, когда заказчик попросил указать сокращённое название страницы, которое добавлялось в мета-поле. Если в этом не необходимости — удалите строки с 129 по 132.
Для вывода хлебных крошек на странице вставьте код в месте их вывода.
<?php custom_breadcrumbs(); ?
Хлебные крошки будут выглядеть как на этом сайте.
Hello. Worked fine. Bye.
hello everyone thanks for approve
I liked your blog so much.
I would like to thank you for the contribution.
Thank you very much for the invitation :). Best wishes.
PS: How are you?
hello, how can i solve this problem with this page showing? eye
Hi… this code works, but it hooks to the title tag… is it possible to create a custom field («breadcrumb») instead of duplicating the tag title?
Thanks, Nico.
Hi, Nico.
This is already provided in the code. But it only works for pages, not for posts. Create a custom field called breadcrumbs_title and assign it to all pages. If it is also necessary for posts, tell me and I will add the code.
Thanks for the info, I needed it more than ever.