Loop the Loop

Using WordPress loops to display data

Simon Pollard

Full Time Web Developer at 

 

 

 

@smp303

 

https://slides.com/simonp303

The WordPress Loop

<?php
// Start the loop.
while ( have_posts() ) : the_post();

// Code stuff here

// End the loop.
endwhile;
?>

Used to display page data or list of items

such as posts

@smp303

Using A Custom Loop

<?php
$args = array(
    'posts_per_page'  => -1,
    'post_type'       => 'post',
    'post_status'     => 'publish',
    'ordeby'	      => 'date',
    'order'           => 'ASC'
);
?>

Arguments

Used for get_posts()

Helps us define what will be returned

https://developer.wordpress.org/reference/functions/get_posts/

@smp303

Using A Custom Loop

<?php
$posts = get_posts( $args );

// Now loop through the results
foreach ( $posts as $post ) :
    setup_postdata( $post );
    // Allows us to use the post variable in the list template
    set_query_var( 'post', $post );
    get_template_part('list');
endforeach;

wp_reset_postdata();
?>

Get the data

Get our data - then loop through it

Using template parts allows for re-use elsewhere

https://developer.wordpress.org/reference/functions/get_posts/

@smp303

Using A Custom Loop

<div class="post">
    <h2><?php the_title(); ?></h2>
    <?php
    if(has_post_thumbnail($post->ID)) {
	the_post_thumbnail('thumbnail');
    }
    ?>
    <p><a href="<?php the_permalink(); ?>">View Post</a></p>
</div>

List template

This code gets repeated for each item returned

https://developer.wordpress.org/reference/functions/get_template_part/

@smp303

Actual Examples

Or an excuse to show cats...

Mimi and Rambo (In case you wondered)

@smp303

Loop The Loop

By Simon Pollard

Loop The Loop

Using WordPress loops

  • 1,068