WordPress.org

Support

Support » Themes and Templates » Why we need a loop inside page.php template?

Why we need a loop inside page.php template?

  • mariusbratu
    Member

    @mariusbratu

    Hi everyone,

    I was hoping someone can answer my doubts I’m having. So the question is why we need a loop inside page.php template? I don’t understand why we need it as seems that we always have just a single post to display (ie content of that page). Is there any reason to do that?

    Thanks and appreciate any of your answers.
    Marius B.

Viewing 6 replies - 1 through 6 (of 6 total)
  • WPyogi
    Forum Moderator

    @wpyogi

    The loop is what gets and displays any posts – even just one:

    http://codex.wordpress.org/The_Loop

    Michael
    Forum Moderator

    @alchymyth

    ‘technically’ you only need to use the_post(); – this will get the next post object of the loop (or the only post object in a page.php template);
    http://codex.wordpress.org/Function_Reference/the_post

    this might generate an error of there is not post (untested), therefore I would consider it a good habit always to use the full loop code.

    mariusbratu
    Member

    @mariusbratu

    Thank you all for your answers!

    So i think its safe to have the_title() outside of loop. As it will always be a single post. I was concerned that there are situations where the page.php template will list more than one post, and that i wasnt aware of such case.

    My current code looks like this:

    <?php get_header(); ?>
    <div class="container breadcrumb">
        <div class="inner-container clearfix">
    	    <span class="dot"></span>
            <h1 class="h2"><?php the_title(); ?></h1>
        </div>
    </div>
    
    <div class="container">
    	<div class="inner-container clearfix">
    		<?php while (have_posts()) : the_post(); ?>
            <article id="post-<?php the_ID(); ?>" <?php post_class('clearfix'); ?> role="article">
                <section class="entry-content">
                    <?php the_content(); ?>
                </section> <!-- end article section -->
            </article> <!-- end article -->
            <?php endwhile; ?>
    	</div>
    </div>
    <?php get_footer(); ?>
    Michael
    Forum Moderator

    @alchymyth

    So i think its safe to have the_title() outside of loop.

    no – although it might seem to work in most cases, this also might get random results.

    http://codex.wordpress.org/Function_Reference/the_title

    mariusbratu
    Member

    @mariusbratu

    In such case, is there a safe way to have the title of the post outside of loop? Can you please make a suggestion here?

    chaleybgis
    Member

    @chaleybgis

    @mariusbratu

    You should be able to safely echo get_the_title(); outside of the loop,,

Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘Why we need a loop inside page.php template?’ is closed to new replies.