Skip to content
Home » Blog » Computer Science » Web Development » WordPress » Is the WordPress Loop required in single.php?

Is the WordPress Loop required in single.php?

2 minute read

Short answer: no, you do not need the WordPress loop in single.php or any singular template like page.php or product.php.

<?php /* Using the WordPress Loop on single.php */ ?>
<main>
    <?php if( have_posts() ) : while( have_posts() ) : the_post(); ?>
        <article>
            <?php the_content(); ?>
        </article>
    <?php endwhile; endif; ?>
</main>

Calling the functions like the_title() and the_content() will work just fine on those templates without using the WordPress loop:

<?php /* NOT using the WordPress Loop on single.php */ ?>
<main>
    <article>
        <?php the_content(); ?>
    </article>
</main>

WordPress Loop Best Practices

However, it is considered best practice to use the loop because there are actions that get fired from the have_posts() and the_post() functions that WordPress plugins could potentially use. Currently, nothing in WordPress Core uses these actions, but by omitting the loop, you risk losing whatever functionality that a plugin may have hooked into them.

The source code for have_posts() fires off loop_end once the loop has ended while the source code for the_post() fires off loop_start. Want to see this for yourself? Simply add the following snippet to your active theme’s functions.php file to hook into these actions:

add_action('loop_start', function() {
    echo('<h1>Loop Start!</h1>');
}, 0, 10);

add_action('loop_end', function() {
    echo('<h1>Loop End!</h1>');
}, 0, 10);

Now every template that uses the WordPress loop will have those header tags displayed.

An Alternative

If you’re determined to not use the loop within your singular templates but still want them to be future-proofed and compatible in case anything ever does hook into these actions, I highly recommend adding them directly into your singular templates like in the snippet below for example.

<?php /* Using Actions Instead of WordPress Loop */ ?>
<main>
    <article>
        <?php
            global $wp_query;
            do_action_ref_array( 'loop_start', array( $wp_query ) ); 
            the_content(); 
            do_action_ref_array( 'loop_end', array( $wp_query ) );
        ?>
    </article>
</main>

If you still have that snippet in your functions.php file, then you’ll see that the header tags still display with this alternative, so nothing broke by removing the loop! Cheers!


Featured photo by Shahadat Rahman on Unsplash.

Nobody has commented on this yet, be the first!

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.