Load wordpress posts by category Slug from the URL

By December 4, 2012 Wordpress

Here is a quick wordpress development tip to help you load posts into the wordpress loop based off the category slug in the URL. This assumes you are using the postname permalink structure for your url, e.g. mysite.com/category/testcategry.

In your functions file add this function:
[php] function getLastPathSegment($url) {
$path = parse_url($url, PHP_URL_PATH);
$pathTrimmed = trim($path, ‘/’);
$pathTokens = explode(‘/’, $pathTrimmed);
if (substr($path, -1) !== ‘/’) {
array_pop($pathTokens);
}
return end($pathTokens);
}
[/php]

This function will process the slug we will pass to it from the template file. In your template file:

[php] $slug = getLastPathSegment($_SERVER[‘REQUEST_URI’]); // Get the last slug item
$category = get_category_by_slug($slug); // Load the category
query_posts(‘showposts=-1&post_status=publish&cat=’.$category —>cat_ID); // Load the posts

// WordPress Loop as normal
[/php]

About Wordpress Sherpa

I am Sherpa. I heart mountains, permaculture, awareness, sustainability, local food, and Wordpress websites. I code, design, fix, update, migrate, host everything wordpress. Find me on Facebook or .

20% Off WP Engine

Leave a Reply