blog

Load wordpress posts by category Slug from the URL

published in

Wordpress

comments

0

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:

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);
}

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

$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
This entry was posted in Wordpress and tagged . Bookmark the permalink.

Comments are closed.