PHP Development

Fetch and display list of all WordPress posts in a page

In WordPress, the have_posts() function serves as a gatekeeper, checking whether there are posts available in the current query. Once have_posts() confirms that there are indeed posts to
Screenshot of arrays image

As WordPress created different functions that can be called anywhere in the website, we can use different functions that are pre-built with WordPress just by calling functions.

  1. In WordPress, the have_posts() function serves as a gatekeeper, checking whether there are posts available in the current query. Once have_posts() confirms that there are indeed posts to display, the_post() function comes in
  2. the_post(); function in WordPress helps to loop through posts and get post complete information.
  3. By calling the_title(); function in WordPress after have_posts() function, we can get the title of all posts.
  4. By calling the_body(); function we can access content of wp posts

While accessing wp post data adding <a></a> tag and adding the_permalink(); function inside href="<?php the_permalink(); ?>" adds the link of singular post.

So, to finalize, to access all of available posts in WordPress and display all of them in one page, you can use code snippet like this one.

<?php
while(have_posts()){
the_post(); ?>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<?php the_content(); ?>
<?php }
?>

Generally, while you are using take a note of the <?php at the top and ?> at the bottom. If you already included it, you may not need to copy all of it.

  • the_permalink() inside the <a> tag fetches links of each post and adds the link to the post in the posts page to each title as we assigned the link for titles
  • the_post() is used to fetch all the information of each post in array
  • have_posts() function is called to check if there are any post in WordPress then while have_posts() is true, the_post() will continue fetching each post data.
  • the_title() and the_content() are used to fetch the title and the content parts of the_post()

—- Tankyou for reading —-

Shares:

Related Posts

Top Categories

PHP Development
22
WordPress Theme Development
21
Wordpress Development
18
WordPress JS Development
13
Show Comments (0)
Leave a Reply

Your email address will not be published. Required fields are marked *