I have an unusual situation I put myself in.
I’m making a custom theme and I want to display a list of subcategory posts with its own URL like this:
https://domain.com/category/sub-category
So far, https://domain.com/category
creates and lists sub-categories as expected. When the sub-categories https://domain.com/category/sub-category
is accessed, I get a 404 error.
Here’s my code for the listing of the subcategories:
$cat_ID = get_category_by_slug( 'category' )->cat_ID;
$categories = get_categories( [
'parent' => $cat_ID
]);
echo '<ul>';
foreach ($categories as $item) :
printf( '<li><a href="/categories/%s">%s</a> (%d Articles)</li>', $item->slug, $item->name, $item->count);
endforeach;
echo '</ul>';
Here’s the code for my subcategory listing its posts:
global $wp;
$slug = $wp->query_vars[ 'cat' ];
$cat_name = get_category_by_slug( $slug )->name;
if ( $cat_name != null) :
$posts = get_posts( [
'posts_per_page' => -1,
'category_name' => $slug,
'order' => 'ASC',
'orderby' => 'title'
] );
echo '<ul>';
foreach ( $posts as $post ) :
printf( '<li><p><a href="%s/%s">%s</a><br>%s</p></li>', $slug, $post->post_name, $post->post_title, $post->post_excerpt );
endforeach;
echo '</ul>';
The only way for the subcategory’s post is to properly display is to use the URL: https://domain.com/sub-category
which is something I do not want.
So, how do I list the posts of the subcategories of the categories using the URL: https://domain.com/category/sub-category
?