WordPress


The Loop (main WordPress loop) All Versions

1.0
1.2
1.5
2.0
2.1
2.2
2.3
2.5
2.6
2.7
2.8
2.9
3.0
3.1
3.2
3.3
3.4
3.5
3.6
3.7
3.8
3.9
4.0
4.1
4.2
4.3
4.4
4.5
4.6
4.7

This draft deletes the entire topic.

Introduction

Introduction

expand all collapse all

Examples

  • 2

    You can also use loop with curly brackets like this:

    if ( have_posts() ) {
        while ( have_posts() ) {
    
            the_post(); 
            var_dump( $post );
        
        }
    }
    
  • 2

    Each time WordPress loads the page, it will run main loop.

    The loop is the way to iterate over all elements related to the page you are currently on.

    Main loop will work on a global WP_Query object. The query has a globalized method have_posts(), that allows us to loop through all results. Finally inside the loop you can call the_post() method (also as a global function), which sets global post object to the current post inside the loop, and sets the postdata to the current post. Thanks to this you can call functions like the_title, the_content, the_author (template tags) directly inside the loop.

    For example if you are on posts lists, main loop will contain a query object with all posts.

    If you are on single post (or page), it will contain a query with single post (page) you are currently on.

    if ( have_posts() ) : 
        while ( have_posts() ) :
            the_post();
            var_dump( $post );
        endwhile;
    endif;
    
  • 2

    If you want to handle such scenario just add an if/else statement.

    if ( have_posts() ) : while ( have_posts() ) : 
    
        the_post(); 
        var_dump( $post );
    
    endwhile; else :
    
        __('This Query does not have any results');    
    
    endif;
    
Please consider making a request to improve this example.

Syntax

Syntax

Parameters

Parameters

Remarks

Remarks

Still have a question about The Loop (main WordPress loop)? Ask Question

Topic Outline