Search code examples
wordpresshashtagwp-list-categories

WordPress: Add a hashtag to the category-slugname


I'm trying to find a solution to remove e.g. http://website/drinks/, then add a hashtag at the beginning of the categories-slugname e.g. #coffee.

Current situation:

<ul>
<li class="cat-item-1"><a href="http://website/drinks/coffee/">Coffee</a></li>
<li class="cat-item-2"><a href="http://website/drinks/tea/">Tea</a></li>
</ul>

Desired situation:

<ul>
<li class="cat-item-1"><a href="#coffee">Coffee</a></li>
<li class="cat-item-2"><a href="#tea">Tea</a></li>
</ul>


The solution must be codded in functions.php of my WordPress theme. I'm not a master at coding, but I've founded a way to add a hash at the ending of the URL.

add_filter('wp_list_categories', 'filter_categories', 10, 2);

function filter_categories($output, $args=array()){
      return preg_replace('/(\<a\shref=\"?[^\>]+?)\"/', '$1#"', $output);
}

Output:

<ul>
<li class="cat-item-1"><a href="http://website/drinks/coffee/#">Coffee</a></li>
<li class="cat-item-2"><a href="http://website/drinks/tea/#">tea</a></li>
</ul>

Unfortunately this is for away from my desired situation... Can anyone please help me out?


Solution

  • Try this:

    add_filter('wp_list_categories', function($html, $args) {
    
        $pattern = '/https?:\/\/([^\/]+)\/([^\/]+)\/?/';
    
        $html = preg_replace($pattern, '#', $html);
    
        return preg_replace('/\/["\']/', '"', $html);
    
    }, 10, 2);