// Get the Humor category
$cat = get_term_by( 'slug', 'humor', 'category' );
// Get the sub-categories under Humor
$sub_cats = get_terms(
'category',
array(
'child_of' => $cat->term_id,
'hide_empty' => false,
)
);
// Collate the term ids of all the sub-categories AND the parent category
$cat_ids = array_map(
function ( $value ) { return $value->term_id; },
$sub_cats
);
array_unshift( $cat_ids, $cat->term_id );
// Retrieve only posts belonging to Humor and its sub-categories
$cat_posts = get_posts( array( 'category__in' => $cat_ids ) );
foreach ( $cat_posts as $cat_post ) {
var_dump( $cat_post->post_title );
}
Strictly speaking, “Humor” would be a term under the “Categories” taxonomy (Admin > Posts > Categories). For example, I can create a new “Colors” taxonomy, add “Red”, “Green”, “Blue”, and assign them when editing a post. Just FYI 🙂
I was thrilled when I saw this page in Google because this is exactly what I want. I want to be able to have a page dedicated to a single category. But not truly understanding WordPress that well, I’m not sure where to put the code zionsg pasted above. So question #1, in what file do I paste that code?
Question #2: I want to remove that same category from my blog. Is there a simple way to do that? (I assume that’s in Google somewhere — I haven’t gotten to that point yet — but I thought I’d ask here.)
Question #3: Is there a way to order the posts?
Most important, Question #1.
Thanks!
-
This reply was modified 8 years, 8 months ago by
rowlandville.
-
This reply was modified 8 years, 8 months ago by
rowlandville.
For Question #1:
Using the example of the Humor category, you can put the code in page-humor.php, where “humor” is the the slug of the Humor page (presumably set up to show all the posts from the Humor category). Reference: https://developer.wordpress.org/themes/template-files-section/page-template-files/page-templates/#page-templates-within-the-template-hierarchy
For Question #2:
Probably Dashboard > Categories?
For Question #3:
The sorting can be done via the orderby and order arguments in the get_posts() call. Reference: https://codex.wordpress.org/Template_Tags/get_posts
I added the code you gave above and placed it inside the loop. I got this output on the page:
string(72) “Post One” string(30) “Post Two” string(31) “Post Three” string(29) “Post Four” string(36) “Post Five”
Those five names are the post names. In addition, the page content — content that I wrote in the page itself, not a post — did not show up. Any idea what I’m doing wrong?
It appears that the text from the page IS showing up. Sorry for that mistake. But the categories are not showing up.
The names of the categories can be retrieved from $cat->name
and the name
property of each sub-category in $sub_cats
.