Search code examples
phpwordpressbreadcrumbs

Dynamically get page link based on breadcrumb level


I'm trying to create a breadcrumb menu via PHP and have the following so far:

<?php

// 1. Get URL
$crumbs = explode("/",$_SERVER["REQUEST_URI"]);
$address = 'http://'.$_SERVER['HTTP_HOST'];

// 2. Strip extras
foreach($crumbs as $crumb){
    $crumb = ucfirst(str_replace(array(".php","_"),array(""," "),$crumb) . ' ');
    echo "<a href=".$address.">"."<span class='crumbMenu'>".$crumb."</span></a>";
}

?>

Let's say I have the following page hierarchy: Products > Products Level 2 > Products Level 3

The above code will spit out:

Products
Products Level 2
Products Level 3

Which is correct. However, the links are not.

After reading up on HTTP_HOST, I'm certain my approach is wrong, but unsure on what other approach I can take to dynamically get each crumb items link?

Links I am getting:

localhost:8080

Links I am expecting:

  • Products: /products

  • Products Level 2: /products/products-level-2

  • Products Level 3: /products/products-level-2/products-level-3


Solution

  • You seem to have forgotten about adding routes to $address variable, so all your breadcrumbs point to base server address. Try the following:

    <?php
    
    // 1. Get URL
    $crumbs = explode("/",$_SERVER["REQUEST_URI"]);
    $address = 'http://'.$_SERVER['HTTP_HOST'];
    
    // 2. Strip extras
    $build = $address.'/products';
    foreach($crumbs as $crumb){
        if(in_array($crumb, [$_SERVER['HTTP_HOST'], 'products'])) {
            continue;
        }
        $build .= '/'.$crumb;
        $crumb = ucfirst(str_replace(array(".php","_"),array(""," "),$crumb) . ' ');
        echo "<a href=".$address.$build.">"."<span class='crumbMenu'>".$crumb."</span></a>";
    }
    
    ?>