Reputation: 13890
I have my own theme and I'd like to display posts on my home page from a specific category.
So far I've achieved it like this:
<?php
global $post;
$args = array( 'numberposts' => 10, 'category' => 6 );
$posts = get_posts( $args );
foreach( $posts as $post ): setup_postdata($post);
?>
<divs with the_title() the_excerpt() etc ></div>
<?php
endforeach;
?>
But what if I want to get the category by a its slug? Or is it possible to simply make a category selection box in from within the admin panel?
Upvotes: 13
Views: 77719
Reputation: 1240
You can simply pass slug in the get_posts
method of WordPress
suppose your category slug is ice-cake
$args = array('numberposts' => 10, 'category' => 'ice-cake');
$posts = get_posts($args);
For more info : https://developer.wordpress.org/reference/functions/get_posts/
Upvotes: 0
Reputation: 2136
Replace your category
parameter with category_name
<?php
global $post;
$args = array( 'numberposts' => 10, 'category_name' => 'cat-slug' );
$posts = get_posts( $args );
foreach( $posts as $post ): setup_postdata($post);
?>
<divs with the_title() the_excerpt() etc ></div>
<?php endforeach; ?>
For more info: http://codex.wordpress.org/Class_Reference/WP_Query#Parameters
Upvotes: 48
Reputation: 96
suppose you have category name 'ice cakes' and category slug as 'ice-cakes', then our code to retrieve post under category 'ice cakes' is as follows:
<?php
$args = array( 'posts_per_page' => 3,
'category_name' => 'ice-cakes' );
$icecakes = get_posts( $args );
foreach ( $icecakes as $post ) : setup_postdata( $post ); ?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php endforeach;
wp_reset_postdata(); ?>
Upvotes: 4