Simon Pollard
Web developer
Using WordPress loops to display data
Full Time Web Developer at
@smp303
https://slides.com/simonp303
<?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
<?php
$args = array(
'posts_per_page' => -1,
'post_type' => 'post',
'post_status' => 'publish',
'ordeby' => 'date',
'order' => 'ASC'
);
?>
Used for get_posts()
Helps us define what will be returned
https://developer.wordpress.org/reference/functions/get_posts/
@smp303
<?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 our data - then loop through it
Using template parts allows for re-use elsewhere
https://developer.wordpress.org/reference/functions/get_posts/
@smp303
<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>
This code gets repeated for each item returned
https://developer.wordpress.org/reference/functions/get_template_part/
@smp303
Mimi and Rambo (In case you wondered)
@smp303
By Simon Pollard
Using WordPress loops