Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get posts from category using the slug?

Tags:

wordpress

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?

like image 321
Nips Avatar asked Nov 02 '12 20:11

Nips


People also ask

How do you get post by category slug?

3 Answers. Show activity on this post. <? php global $post; $args = array( 'numberposts' => 10, 'category_name' => 'cat-slug' ); $posts = get_posts( $args ); foreach( $posts as $post ): setup_postdata($post); ?>

How do I get post by category name in WordPress?

Now, if you want to display all your posts from a specific category on a separate page, WordPress already takes care of this for you. To find the category page, you simply need to go to Posts » Categories » View page and click on the 'View' link below a category.

How do I find the slug of a category in WordPress?

If you want to get category details by category name , category slug , and category ID then you should use get_term_by() .


1 Answers

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

like image 65
loQ Avatar answered Oct 13 '22 03:10

loQ