Quantcast
Channel: WordPress Cheat Sheets » admin
Viewing all articles
Browse latest Browse all 39

How to Get a List of WordPress Posts from a Particular Category

$
0
0

This code snippet should come in handy if you need to find a list of posts from a category and then do something with that post list.

Use the following same code to retrieve a list of pots that belong to a particular category.

$category_name = "My Category Name";//TODO - specify the category name
$result = get_term_by('name', $category_name, 'category', ARRAY_A);
$cat_id = $result['term_id'];//The id of the category

$args = array(
'category'        => $cat_id,
'orderby'         => 'post_date',
'order'           => 'DESC',
'post_type'       => 'post',
'post_status'     => 'publish',
'suppress_filters' => true
);
$posts_array = get_posts( $args );//This will retrieve the posts

foreach($posts_array as $post){
//TODO - do something with the post data
echo "Post ID: " . $post->ID;
echo "<br />Post Title: " . $post->post_title;
}

Look for the “TODO” markers in the above code snippet and adjust the values to suite your needs.


Viewing all articles
Browse latest Browse all 39

Trending Articles