Asked 6 years ago
27 Jun 2017
Views 1126
Cimb

Cimb posted

How to get posts by category id or category name in wordpress ?


 
global $wpdb, $post;
 
$str    = "SELECT $wpdb->posts.* FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish'";
$result = $wpdb->get_results( $str );



where can i put category name or category id to get posts for particular category ?
hanuman

hanuman
answered Jun 24 '23 00:00

Get posts by category ID:


$category_id = 121221; // Replace 121221 with the category ID you want to query

$args = array(
    'cat' => $category_id,
    'posts_per_page' => -1 // Set the number of posts to display (-1 for all posts)
);

$query = new WP_Query($args);

// The Loop
if ($query->have_posts()) {
    while ($query->have_posts()) {
        $query->the_post();
        // Display post information here
        the_title();
        // ...
    }
} else {
    // No posts found
}

// Restore original post data
wp_reset_postdata();

iptracker

iptracker
answered Jun 24 '23 00:00

Get posts by category name:


$category_name = 'my-category'; // Replace 'my-category' with the category slug or name you want to query

$category = get_category_by_slug($category_name);

if ($category) {
    $args = array(
        'cat' => $category->term_id,
        'posts_per_page' => -1 // Set the number of posts to display (-1 for all posts)
    );

    $query = new WP_Query($args);

    // The Loop
    if ($query->have_posts()) {
        while ($query->have_posts()) {
            $query->the_post();
            // Display post information here
            the_title();
            // ...
        }
    } else {
        // No posts found
    }

    // Restore original post data
    wp_reset_postdata();
} else {
    // Category not found
}

Post Answer