sinanisler logo

Advanced Breadcrumbs Shortcode, WordPress

Short code : [custom_breadcrumbs]

How it works? Examples;

Home > Category 1 > Category 2 > Post Title

Home > Category Name

Home > Tag Name

Home > Parent Page 1 > Parent Page 2 > Current Page Title

Home > Current Page Title

Home > Author Name

Home > Search results for “example query”

….etc



// [custom_breadcrumbs]   shortcode


function custom_breadcrumbs() {

    // Define the breadcrumb structure
    $separator = '<span> > </span>'; // Separator between breadcrumbs
    $home_title = 'Home'; // Text for the home link

    // If it is the front page, return early
    if (is_front_page()) {
        return '';
    }

    // Start the breadcrumbs output
    $breadcrumbs = '<a href="' . get_home_url() . '">' . $home_title . '</a>' . $separator;

    if (is_single()) {
        // For single post, get all categories and post title
        $categories = get_the_category();
        if ($categories) {
            foreach ($categories as $category) {
                $breadcrumbs .= '<a href="' . get_category_link($category->term_id) . '">' . $category->name . '</a>' . $separator;
            }
        }
        $breadcrumbs .= '<span>' . get_the_title() . '</span>';

    } elseif (is_category()) {
        // For category archive page
        $breadcrumbs .= '<span>' . single_cat_title('', false) . '</span>';

    } elseif (is_page()) {
        // For regular pages (not posts)
        if ($post->post_parent) {
            $parent_id  = $post->post_parent;
            $breadcrumbs_array = array();
            while ($parent_id) {
                $page = get_page($parent_id);
                $breadcrumbs_array[] = '<a href="' . get_permalink($page->ID) . '">' . get_the_title($page->ID) . '</a>';
                $parent_id  = $page->post_parent;
            }
            $breadcrumbs_array = array_reverse($breadcrumbs_array);
            $breadcrumbs .= implode($separator, $breadcrumbs_array) . $separator;
        }
        $breadcrumbs .= '<span>' . get_the_title() . '</span>';

    } elseif (is_tag()) {
        // For tag archive page
        $breadcrumbs .= '<span>' . single_tag_title('', false) . '</span>';

    } elseif (is_author()) {
        // For author archive page
        $breadcrumbs .= '<span>' . get_the_author() . '</span>';

    } elseif (is_date()) {
        // For date archive page
        $breadcrumbs .= '<span>' . get_the_time('F Y') . '</span>';

    } elseif (is_search()) {
        // For search results page
        $breadcrumbs .= '<span>Search results for "' . get_search_query() . '"</span>';

    } elseif (is_404()) {
        // For 404 error page
        $breadcrumbs .= '<span>404 - Page not found</span>';
    }

    return $breadcrumbs;
}

// Register shortcode [custom_breadcrumbs]
add_shortcode('custom_breadcrumbs', 'custom_breadcrumbs');


Leave the first comment