Follow these steps to create a custom page template that will display a list of posts as a grid:
- Open the wp-content/themes/twentytwentychild folder using a file manager.
- Create a new template called post-grid.php.
- Add the following code to the post-grid.php file, define it as a template, and save the changes:
<?php /* Template Name: Post Grid */ ?>
- Add the following code after the template name definition to load the header and retrieve the posts:
<?php
get_header();
$post_list = new WP_Query(array('post_type'=>'post',
'post_status'=>'publish', 'posts_per_page'=>-1));
?>
- Now, we can add the following template code after the code in step 4. This code will be used to display the posts list:
<?php if ( $post_list->have_posts() ) : ?>
<div id="list-post-panel">
<ul>
<?php while ( $post_list->have_posts() ) :
$post_list->the_post();
$image = get_the_post_thumbnail_url( get_the_ID()); ?>
<li>
<div class="post-list-featured-image"><img src="<?php
echo $image; ?>" /></div>
<div class="post-list-title"><a href="<?php
the_permalink(); ?>"><?php the_title(); ?></a></div>
</li>
<?php endwhile; ?>
</ul>
<?php wp_reset_postdata(); ?>
<?php else : ?>
<p><?php _e( 'There no posts to display.' ); ?></p>
<?php endif; ?>
</div>
<?php get_footer(); ?>
- Add the following styles to the style.css file of the Twenty Twenty child theme to display the post list as a grid:
#list-post-panel ul { width : 100%; list-style:none; }
#list-post-panel li{
width: 31%;
margin: 1%;
padding: 1%;
float: left;
background: #eee;
list-style: none;
text-align: center;
border: 1px solid #cfcfcf;
}
.post-list-featured-image img{
width: 100%;
height: 200px;
}
- Log in to the site as an administrator.
- Click the Posts menu,
- Click the Add New button to create a new post.
- Set the title for the post to Grid 1 and upload a featured image using the Set featured image button in the Featured image section:
- Click the Publish button to create the post.
- Follow steps 8 to 11 and create two more posts called Grid 2 and Grid 3.
- Click the Pages menu.
- Click the Add New button to create a new page.
- Add a title for the page and select Post Grid as the template under the Page Attributes | Template settings.
- Click the Publish button to create the page.
Now, you can view this page on the frontend. Here, you will see a grid-based post list, as shown in the following screenshot:
Here, we have a grid-based post list design with a three-column layout. This is a basic version of a modern grid template in order to keep up with the scope of this book.
If you are not getting a similar output, make sure that you clear your browser cache and refresh the page a few times to update the CSS and load the design. The output will vary, depending on the images you set as the featured images for the posts.
You can improve this design with animation effects and AJAX-based lazy loading.