WordPress.org

Ready to get started?Download WordPress

Forums

Why we need a loop inside page.php template? (7 posts)

  1. mariusbratu
    Member
    Posted 1 year ago #

    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.

  2. WPyogi
    Volunteer Moderator
    Posted 1 year ago #

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

    http://codex.wordpress.org/The_Loop

  3. alchymyth
    The Sweeper & Moderator
    Posted 1 year ago #

    '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.

  4. mariusbratu
    Member
    Posted 1 year ago #

    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(); ?>
  5. alchymyth
    The Sweeper & Moderator
    Posted 1 year ago #

    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

  6. mariusbratu
    Member
    Posted 1 year ago #

    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?

  7. chaleybgis
    Member
    Posted 9 months ago #

    @mariusbratu -

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

Topic Closed

This topic has been closed to new replies.

About this Topic