How to get all post by categories in wordpress?

Member

by lizzie , in category: PHP CMS , 7 months ago

How to get all post by categories in wordpress?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by deron , 7 months ago

@lizzie 

To get all posts by categories in WordPress, you can use the built-in function get_posts() along with the category parameters. Here's an example of how to achieve this:

  1. Open your theme's functions.php file or create a custom plugin.
  2. Add the following code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
function get_posts_by_category($category_name) {
    // Get the category ID from the name
    $category = get_category_by_slug($category_name);
    $category_id = $category->term_id;

    // Setup the arguments for the query
    $args = array(
        'post_type' => 'post', // Select the post type (default is 'post')
        'category__in' => array($category_id), // Select the category ID
        'posts_per_page' => -1,  // Show all posts of the category
    );

    // Perform the query
    $posts = get_posts($args);

    // Loop through each post
    foreach ($posts as $post) {
        // Output the post title, content, or any other data you need
        echo '<h2>' . get_the_title($post) . '</h2>';
        echo '<p>' . get_the_content($post) . '</p>';
    }
}


  1. Replace 'post' with the post type you want to display (e.g., 'page' or a custom post type) if necessary.
  2. Now you can call the function get_posts_by_category('category-slug'); in your template file or wherever you need to display the posts of a specific category.


Make sure to replace 'category-slug' with the actual slug of the category you want to display posts from.