Перейти до змісту
setbenson
0 Написати

// 21.02.2022 Переглядів: 3 978

Хлібні крихти (breadcrumbs) без плагіна на WordPress

Хлібні крихти (breadcrumbs) на WordPress

Хлібні крихти (breadcrumbs) — це навігація, що показує шлях від головної сторінки до поточної. Усі сторінки в ланцюжку — посилання, тож легко повернутися на будь-який рівень назад. Зазвичай крихти розміщують угорі сторінки.

Для WordPress є чимало плагінів, але вони не завжди підходять. Код нижче додає хлібні крихти, які одразу запрацюють на вашому сайті.

Вставте код у файл functions.php, що лежить у папці теми вашого сайту:

// Хлібні крихти
function custom_breadcrumbs() {
    // Налаштування
    $separator = '>'; // Роздільник крихт
    $breadcrums_id = 'breadcrumbs'; // id блоку
    $breadcrums_class = 'breadcrumbs'; // class крихт
    $home_title = 'Головна'; // Назва головної сторінки в хлібних крихтах
    // Якщо у вас є власні таксономії, вкажіть їх у змінній нижче (наприклад, product_cat для WooCommerce)
    $custom_taxonomy = 'product_cat';
    // Отримуємо запис і запит
    global $post, $wp_query;
    // Не показувати на головній
    if (!is_front_page()) {
        // Початок хлібних крихт
        echo '<ul class="' . $breadcrums_class . '">
 	        <li style="list-style-type: none;">
                  <ul class="' . $breadcrums_class . '">';
        // Головна
        echo '<li class="item-home"><a class="bread-link bread-home" title="' . $home_title . '" href="' . get_home_url() . '">' . $home_title . '</a></li>
                  </ul>
                </li>
             </ul>';
        echo '<ul class="' . $breadcrums_class . '">
 	<li style="list-style-type: none;">
<ul class="' . $breadcrums_class . '">
 	<li class="separator separator-home">' . $separator . '</li>
</ul>
</li>
</ul>';
        if (is_archive() && !is_tax() && !is_category() && !is_tag()) {
            echo '<ul class="' . $breadcrums_class . '">
 	<li style="list-style-type: none;">
<ul class="' . $breadcrums_class . '">
 	<li class="item-current item-archive"><strong class="bread-current bread-archive">' . post_type_archive_title($prefix, false) . '</strong></li>
</ul>
</li>
</ul>
';
        } else if (is_archive() && is_tax() && !is_category() && !is_tag()) { // Якщо це запис власного типу
            $post_type = get_post_type();
            if ($post_type != 'post') {
                $post_type_object = get_post_type_object($post_type);
                $post_type_archive = get_post_type_archive_link($post_type);
                echo '<ul class="' . $breadcrums_class . '">
 	<li style="list-style-type: none;">
<ul class="' . $breadcrums_class . '">
 	<li class="item-cat item-custom-post-type-' . $post_type . '"><a class="bread-cat bread-custom-post-type-' . $post_type . '" title="' . $post_type_object->labels->name . '" href="' . $post_type_archive . '">' . $post_type_object->labels->name . '</a></li>
</ul>
</li>
</ul>
';
                echo '<ul class="' . $breadcrums_class . '">
 	<li style="list-style-type: none;">
<ul class="' . $breadcrums_class . '">
 	<li class="separator">' . $separator . '</li>
</ul>
</li>
</ul>
';
            }
            $custom_tax_name = get_queried_object()->name;
            echo '<ul class="' . $breadcrums_class . '">
 	<li style="list-style-type: none;">
<ul class="' . $breadcrums_class . '">
 	<li class="item-current item-archive"><strong class="bread-current bread-archive">' . $custom_tax_name . '</strong></li>
</ul>
</li>
</ul>
';
        } else if (is_single()) { // Якщо це запис власного типу
            $post_type = get_post_type();
            if ($post_type != 'post') {
                $post_type_object = get_post_type_object($post_type);
                $post_type_archive = get_post_type_archive_link($post_type);
                echo '<ul class="' . $breadcrums_class . '">
 	<li style="list-style-type: none;">
<ul class="' . $breadcrums_class . '">
 	<li class="item-cat item-custom-post-type-' . $post_type . '"><a class="bread-cat bread-custom-post-type-' . $post_type . '" title="' . $post_type_object->labels->name . '" href="' . $post_type_archive . '">' . $post_type_object->labels->name . '</a></li>
</ul>
</li>
</ul>
';
                echo '<ul class="' . $breadcrums_class . '">
 	<li style="list-style-type: none;">
<ul class="' . $breadcrums_class . '">
 	<li class="separator">' . $separator . '</li>
</ul>
</li>
</ul>
';
            }
            // Рубрика
            $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.= '
<ul class="' . $breadcrums_class . '">
 	<li style="list-style-type: none;">
<ul class="' . $breadcrums_class . '">
 	<li class="item-cat">' . $parents . '</li>
</ul>
</li>
</ul>';
                    $cat_display.= '
<ul class="' . $breadcrums_class . '">
 	<li style="list-style-type: none;">
<ul class="' . $breadcrums_class . '">
 	<li class="separator">' . $separator . '</li>
</ul>
</li>
</ul>
';
                }
            }
            // Якщо це запис власного типу у власній таксономії
            $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;
            }
            // Перевіряємо, чи запис у рубриці
            if (!empty($last_category)) {
                echo $cat_display;
                echo '<ul class="' . $breadcrums_class . '">
 	<li style="list-style-type: none;">
<ul class="' . $breadcrums_class . '">
 	<li class="item-current item-' . $post->ID . '"><strong class="bread-current bread-' . $post->ID . '" title="' . get_the_title() . '">' . get_the_title() . '</strong></li>
</ul>
</li>
</ul>
';
                // Інакше — якщо запис у власній таксономії
                
            } else if (!empty($cat_id)) {
                echo '<ul class="' . $breadcrums_class . '">
 	<li style="list-style-type: none;">
<ul class="' . $breadcrums_class . '">
 	<li class="item-cat item-cat-' . $cat_id . ' item-cat-' . $cat_nicename . '"><a class="bread-cat bread-cat-' . $cat_id . ' bread-cat-' . $cat_nicename . '" title="' . $cat_name . '" href="' . $cat_link . '">' . $cat_name . '</a></li>
</ul>
</li>
</ul>
';
                echo '<ul class="' . $breadcrums_class . '">
 	<li style="list-style-type: none;">
<ul class="' . $breadcrums_class . '">
 	<li class="separator">' . $separator . '</li>
</ul>
</li>
</ul>
';
                echo '<ul class="' . $breadcrums_class . '">
 	<li style="list-style-type: none;">
<ul class="' . $breadcrums_class . '">
 	<li class="item-current item-' . $post->ID . '"><strong class="bread-current bread-' . $post->ID . '" title="' . get_the_title() . '">' . get_the_title() . '</strong></li>
</ul>
</li>
</ul>
';
            } else {
                echo '<ul class="' . $breadcrums_class . '">
 	<li style="list-style-type: none;">
<ul class="' . $breadcrums_class . '">
 	<li class="item-current item-' . $post->ID . '"><strong class="bread-current bread-' . $post->ID . '" title="' . get_the_title() . '">' . get_the_title() . '</strong></li>
</ul>
</li>
</ul>
';
            }
        } else if (is_category()) { // На сторінці рубрики
            echo '<ul class="' . $breadcrums_class . '">
 	<li style="list-style-type: none;">
<ul class="' . $breadcrums_class . '">
 	<li class="item-current item-cat"><strong class="bread-current bread-cat">' . single_cat_title('', false) . '</strong></li>
</ul>
</li>
</ul>
';
        } else if (is_page()) {
            // Звичайна сторінка
            if ($post->post_parent) {
                // Якщо в сторінки є батьківська
                $anc = get_post_ancestors($post->ID);
                // Батьківські сторінки в правильному порядку
                $anc = array_reverse($anc);
                // Цикл по батьківських сторінках
                if (!isset($parents)) $parents = null;
                foreach ($anc as $ancestor) {
                    $parents.= '
<ul class="' . $breadcrums_class . '">
 	<li style="list-style-type: none;">
<ul class="' . $breadcrums_class . '">
 	<li class="item-parent item-parent-' . $ancestor . '"><a class="bread-parent bread-parent-' . $ancestor . '" title="' . get_the_title($ancestor) . '" href="' . get_permalink($ancestor) . '">' . get_the_title($ancestor) . '</a></li>
</ul>
</li>
</ul>
';
                    $parents.= '
<ul class="' . $breadcrums_class . '">
 	<li style="list-style-type: none;">
<ul class="' . $breadcrums_class . '">
 	<li class="separator separator-' . $ancestor . '">' . $separator . '</li>
</ul>
</li>
</ul>
';
                }
                // Виводимо батьківські сторінки
                echo $parents;
                // Поточна сторінка
                echo '<ul class="' . $breadcrums_class . '">
 	<li style="list-style-type: none;">
<ul class="' . $breadcrums_class . '">
 	<li class="item-current item-' . $post->ID . '"><strong title="' . get_the_title() . '"> ' . get_the_title() . '</strong></li>
</ul>
</li>
</ul>
';
            } else {
                // Якщо батьківських немає — просто поточна сторінка
                echo '<ul class="' . $breadcrums_class . '">
 	<li style="list-style-type: none;">
<ul class="' . $breadcrums_class . '">
 	<li class="item-current item-' . $post->ID . '"><strong class="bread-current bread-' . $post->ID . '"> ' . get_the_title() . '</strong></li>
</ul>
</li>
</ul>
';
            }
        } 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 '<ul class="' . $breadcrums_class . '">
 	<li style="list-style-type: none;">
<ul class="' . $breadcrums_class . '">
 	<li class="item-current item-tag-' . $get_term_id . ' item-tag-' . $get_term_slug . '"><strong class="bread-current bread-tag-' . $get_term_id . ' bread-tag-' . $get_term_slug . '">' . $get_term_name . '</strong></li>
</ul>
</li>
</ul>
';
        } elseif (is_day()) {
            // АРХІВ ДНЯ
            // Архів року
            echo '<ul class="' . $breadcrums_class . '">
 	<li style="list-style-type: none;">
<ul class="' . $breadcrums_class . '">
 	<li class="item-year item-year-' . get_the_time('Y') . '"><a class="bread-year bread-year-' . get_the_time('Y') . '" title="' . get_the_time('Y') . '" href="' . get_year_link(get_the_time('Y')) . '">' . get_the_time('Y') . ' Archives</a></li>
</ul>
</li>
</ul>
';
            echo '<ul class="' . $breadcrums_class . '">
 	<li style="list-style-type: none;">
<ul class="' . $breadcrums_class . '">
 	<li class="separator separator-' . get_the_time('Y') . '">' . $separator . '</li>
</ul>
</li>
</ul>
';
            // Архів місяця
            echo '<ul class="' . $breadcrums_class . '">
 	<li style="list-style-type: none;">
<ul class="' . $breadcrums_class . '">
 	<li class="item-month item-month-' . get_the_time('m') . '"><a class="bread-month bread-month-' . get_the_time('m') . '" title="' . get_the_time('M') . '" href="' . get_month_link(get_the_time('Y'), get_the_time('m')) . '">' . get_the_time('M') . ' Archives</a></li>
</ul>
</li>
</ul>
';
            echo '<ul class="' . $breadcrums_class . '">
 	<li style="list-style-type: none;">
<ul class="' . $breadcrums_class . '">
 	<li class="separator separator-' . get_the_time('m') . '">' . $separator . '</li>
</ul>
</li>
</ul>
';
            // Архів дня
            echo '<ul class="' . $breadcrums_class . '">
 	<li style="list-style-type: none;">
<ul class="' . $breadcrums_class . '">
 	<li class="item-current item-' . get_the_time('j') . '"><strong class="bread-current bread-' . get_the_time('j') . '"> ' . get_the_time('jS') . ' ' . get_the_time('M') . ' Archives</strong></li>
</ul>
</li>
</ul>
';
        } else if (is_month()) {
            // АРХІВ МІСЯЦЯ
            // Архів року
            echo '<ul class="' . $breadcrums_class . '">
 	<li style="list-style-type: none;">
<ul class="' . $breadcrums_class . '">
 	<li class="item-year item-year-' . get_the_time('Y') . '"><a class="bread-year bread-year-' . get_the_time('Y') . '" title="' . get_the_time('Y') . '" href="' . get_year_link(get_the_time('Y')) . '">' . get_the_time('Y') . ' Archives</a></li>
</ul>
</li>
</ul>
';
            echo '<ul class="' . $breadcrums_class . '">
 	<li style="list-style-type: none;">
<ul class="' . $breadcrums_class . '">
 	<li class="separator separator-' . get_the_time('Y') . '">' . $separator . '</li>
</ul>
</li>
</ul>
';
            // Архів місяця
            echo '<ul class="' . $breadcrums_class . '">
 	<li style="list-style-type: none;">
<ul class="' . $breadcrums_class . '">
 	<li class="item-month item-month-' . get_the_time('m') . '"><strong class="bread-month bread-month-' . get_the_time('m') . '" title="' . get_the_time('M') . '">' . get_the_time('M') . ' Archives</strong></li>
</ul>
</li>
</ul>
';
        } else if (is_year()) {
            // АРХІВ РОКУ
            echo '<ul class="' . $breadcrums_class . '">
 	<li style="list-style-type: none;">
<ul class="' . $breadcrums_class . '">
 	<li class="item-current item-current-' . get_the_time('Y') . '"><strong class="bread-current bread-current-' . get_the_time('Y') . '" title="' . get_the_time('Y') . '">' . get_the_time('Y') . ' Archives</strong></li>
</ul>
</li>
</ul>
';
        } else if (is_author()) {
            // Архів автора
            // Дані автора
            global $author;
            $userdata = get_userdata($author);
            // Виводимо ім'я автора
            echo '<ul class="' . $breadcrums_class . '">
 	<li style="list-style-type: none;">
<ul class="' . $breadcrums_class . '">
 	<li class="item-current item-current-' . $userdata->user_nicename . '"><strong class="bread-current bread-current-' . $userdata->user_nicename . '" title="' . $userdata->display_name . '">' . 'Author: ' . $userdata->display_name . '</strong></li>
</ul>
</li>
</ul>
';
        } else if (get_query_var('paged')) {
            // Архів із пагінацією
            echo '<ul class="' . $breadcrums_class . '">
 	<li style="list-style-type: none;">
<ul class="' . $breadcrums_class . '">
 	<li class="item-current item-current-' . get_query_var('paged') . '"><strong class="bread-current bread-current-' . get_query_var('paged') . '" title="Page ' . get_query_var('paged') . '">' . __('Page') . ' ' . get_query_var('paged') . '</strong></li>
</ul>
</li>
</ul>
';
        } else if (is_search()) {
            // Результати пошуку
            echo '<ul class="' . $breadcrums_class . '">
 	<li style="list-style-type: none;">
<ul class="' . $breadcrums_class . '">
 	<li class="item-current item-current-' . get_search_query() . '"><strong class="bread-current bread-current-' . get_search_query() . '" title="Search results for: ' . get_search_query() . '">Search results for: ' . get_search_query() . '</strong></li>
</ul>
</li>
</ul>
';
        } elseif (is_404()) {
            // Сторінка 404
            echo '<ul class="' . $breadcrums_class . '">
 	<li style="list-style-type: none;">
<ul class="' . $breadcrums_class . '">
 	<li>' . 'Error 404' . '</li>
</ul>
</li>
</ul>
';
        }
    }
}

Далі виведіть хлібні крихти в потрібному шаблоні (наприклад, single.php, page.php, archive.php тощо):

<?php custom_breadcrumbs(); ?>

Тепер крихти варто трохи оформити. Ось базові стилі — додайте цей код у файл стилів .css:

#breadcrumbs{
    list-style:none;
    margin:10px 0;
    overflow:hidden;
}
  
#breadcrumbs li{
    display:inline-block;
    vertical-align:middle;
    margin-right:15px;
}
  
#breadcrumbs .separator{
    font-size:18px;
    font-weight:100;
    color:#ccc;
}

Якщо ви новачок і не маєте досвіду з кодом WordPress, краще скористатися плагіном: Yoast SEO має хлібні крихти серед своїх функцій.

Що думаєте?

Пошта не публікується. Коментар з’явиться після перевірки.