WP Snipp Ninja

How to create simple WordPress Loop for posts and display it in single.php WordPress Theme file?

Author: Dimitar Krumov | Posted on: December 18, 2018 |


Here is a simple snippet for single.php Loop

With the code below you can display you single post/page content and get header.php and footer.php


1. The WordPress Loop starts with


<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

Then our WordPress Loop should continue with both most important part of every page

  • the_title
  • the_content

2. Add this code to display your page/post title inside your WordPress Page/post Loop


<?php the_title(); ?>

3. Display the Content of your WordPress page/post


<?php the_content(); ?>

4. End your WordPress Loop


<?php endwhile; else : ?>
        <p><?php esc_html_e( 'Sorry, no posts matched your criteria. Please try different search or visit our home page' ); ?></p>
<?php endif; ?>

5. Support any additional content markups in your loop


You can always echo any additional content like share buttons and any meta data from your single post or page like

  • the_date
  • tags
  • categories
  • breadcrumb

6. View the full WordPress Loop code below


<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php the_title(); ?>
<?php the_content(); ?>
<?php endwhile; else : ?>
        <p><?php esc_html_e( 'Sorry, no posts matched your criteria. Please try different search or visit our home page' ); ?></p>
<?php endif; ?>

Please: Note

If you want this code to work for you your single.php or page.php file should use both default WordPress functions to get header and footer content like below

<?php get_header();?>
<?php get_header();?>

So the actual WordPress Loop for you single.php or page.php should look like this


<?php get_header();?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php the_title(); ?>
<?php the_content(); ?>
<?php endwhile; else : ?>
        <p><?php esc_html_e( 'Sorry, no posts matched your criteria. Please try different search or visit our home page' ); ?></p>
<?php endif; ?>
<?php get_footer();?>

Don’t forget to wrap it in HTML and style it with CSS

 

Article keywords

  • About the Author

     Dimitar Krumov

    Hello my name is Dimitar Krumov I am from Sofia Bulgaria but live in Varna on the Black Sea coast.I am a Web Developer since 2002 working in different Web Projects most of them are international and business-related. Some of my knowledge and skills but not limited to WordPress, HTML, CSS, Google Stack, Analytics, SEO and more..


    Follow Dimitar Krumov on Social Media

    Leave a Reply

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