To retrieve all posts in WordPress, you can use the WP_Query
class or helper functions like get_posts()
or get_pages()
. Here’s how you can do it:
1. Using WP_Query (Recommended for Advanced Queries)
The WP_Query
class allows you to fetch posts with a lot of customization options.
Basic Example
<?php
$args = array(
'post_type' => 'post', // Post type ('post' for blog posts, or custom post type slug)
'posts_per_page' => -1, // -1 to retrieve all posts
);
$query = new WP_Query($args);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post(); // Setup post data
echo '<h2>' . get_the_title() . '</h2>';
echo '<div>' . get_the_excerpt() . '</div>';
}
wp_reset_postdata(); // Reset post data
} else {
echo 'No posts found.';
}
?>
Additional Query Parameters
You can add filters to refine your query:
- Retrieve posts by a specific category:
$args = array(
'category_name' => 'news', // Slug of the category
);
Retrieve posts by tag:
$args = array(
'tag' => 'featured', // Slug of the tag
);
Retrieve posts within a date range:
$args = array(
'date_query' => array(
array(
'after' => 'January 1st, 2023',
'before' => 'December 31st, 2023',
'inclusive' => true,
),
),
);
2. Using get_posts()
The get_posts()
function is a simpler way to retrieve posts.
Basic Example
<?php
$args = array(
'post_type' => 'post',
'posts_per_page' => -1, // Retrieve all posts
);
$posts = get_posts($args);
if ($posts) {
foreach ($posts as $post) {
setup_postdata($post); // Setup post data
echo '<h2>' . get_the_title($post) . '</h2>';
echo '<div>' . get_the_excerpt($post) . '</div>';
}
wp_reset_postdata();
} else {
echo 'No posts found.';
}
?>
3. Using get_pages()
If you’re retrieving pages instead of posts:
<?php
$pages = get_pages();
foreach ($pages as $page) {
echo '<h2>' . $page->post_title . '</h2>';
echo '<div>' . $page->post_content . '</div>';
}
?>
4. Using REST API (Frontend or External Use)
If you want to fetch posts using JavaScript or for external applications, you can use WordPress’s built-in REST API.
Endpoint for All Posts
https://yourdomain.com/wp-json/wp/v2/posts
Example Fetch Request
fetch('https://yourdomain.com/wp-json/wp/v2/posts')
.then(response => response.json())
.then(data => {
data.forEach(post => {
console.log(post.title.rendered); // Post title
});
});
Best Practices
- Always call
wp_reset_postdata()
after custom queries to avoid conflicts with the main query. - Use pagination if you have a large number of posts to prevent performance issues (
'posts_per_page' => 10
). - Use caching plugins or object caching for better performance when retrieving large datasets.
Would you like help implementing a specific method or customizing the query further?