sinanisler logo

Breadcrumbs, Post, Post Types and Taxonomies, WordPress

The custom_breadcrumbs function generates a breadcrumb navigation for a WordPress site, dynamically creating links based on the type of content being viewed (like categories, posts, or archives). It starts with a link to the home page, then adds specific links depending on whether the viewer is on a post, category, taxonomy term, archive, or a regular page. The breadcrumbs are displayed as an unordered list in HTML, providing a navigational trail for users to follow back to the home page or other sections of the site.

function custom_breadcrumbs() {
    // Start of the breadcrumb list
    echo '<ul class="breadcrumbs">';
    echo '<li><a href="' . get_home_url() . '">Home</a></li>';

    // Check if the current view is a category, single post, taxonomy, or archive page
    if (is_category() || is_single() || is_tax() || is_archive()) {
        $post_type = get_post_type();

        // If the post type is not a standard post, display its type in the breadcrumb
        if ($post_type != 'post') {
            $post_type_object = get_post_type_object($post_type);
            $post_type_archive = get_post_type_archive_link($post_type);
            echo '<li><a href="' . $post_type_archive . '">' . $post_type_object->labels->singular_name . '</a></li>';
        }

        // If viewing a single post, display its categories in the breadcrumb
        if (is_single()) {
            $categories = get_the_category();
            if ($categories) {
                foreach ($categories as $category) {
                    echo '<li><a href="' . get_category_link($category->term_id) . '">' . $category->name . '</a></li>';
                }
            }
            // Display the current post title
            echo '<li>' . get_the_title() . '</li>';
        } elseif (is_tax()) {
            // If viewing a taxonomy, display the current term
            $current_term = get_queried_object();
            echo '<li><a href="' . get_term_link($current_term) . '">' . $current_term->name . '</a></li>';
        } elseif (is_archive()) {
            // If viewing an archive, display the archive title
            $archive_title = post_type_archive_title('', false);
            echo '<li>' . $archive_title . '</li>';
        }
    } elseif (is_page()) {
        // If viewing a page, display the page title
        echo '<li>' . get_the_title() . '</li>';
    }

    // End of the breadcrumb list
    echo '</ul>';
}

// Function call to generate the breadcrumbs
custom_breadcrumbs();

Leave the first comment