jQuery + WordPress – Count the Number of Paths or “Segments” in a URL

Recently, as is often the case, I was working on a WordPress task. I needed to create a search function that would append the current category a user is viewing to a search string. Ultimately, I moved away from search strings passed into a url, and opted to AJAX into a query and return the loop…but, I digress. I figure, overall you can just use the get current category function of WordPress, but in this case, I went with a front-end solution instead (to save time and frustration), because a custom taxonomy is being used, and it might be difficult to ascertain what the taxonomy approach might become if edited (the taxonimies are being populated by a plugin, so it’s not definitely static).

I figure, as long as I can always obtain the last directory we’re in, we know what category is being viewed. Then I just count the number of segments that exist, offset by +1 to avoid the public html dir, and then I grab out the value of the segment that equals that last path.

So, what I decided to do was this:


$(document).ready(function(){
    var url = window.location.href;
    //verify that we're on a category
    if(url.indexOf('category') > 0){
    //count number of 
        var urllength = url.split("/").length - 1 - (url.indexOf("http://")==-1?0:2) + 1;
        current_cat = url.split("/")[urllength]
    } else {
        current_cat = '';
    }
});

Leave a Reply

  • (will not be published)

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>