Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
WordPress 5 Cookbook

You're reading from   WordPress 5 Cookbook Actionable solutions to common problems when building websites with WordPress

Arrow left icon
Product type Paperback
Published in Mar 2020
Publisher Packt
ISBN-13 9781838986506
Length 660 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Rakhitha Nimesh Ratnayake Rakhitha Nimesh Ratnayake
Author Profile Icon Rakhitha Nimesh Ratnayake
Rakhitha Nimesh Ratnayake
Arrow right icon
View More author details
Toc

Table of Contents (16) Chapters Close

Preface 1. Setting Up WordPress and Customizing Settings 2. Customizing Theme Design and Layout FREE CHAPTER 3. Using Plugins and Widgets 4. Publishing Site Content with the Gutenberg Editor 5. Managing Users and Permissions 6. Setting up a Blogging and Editorial Workflow 7. WordPress as an Application Framework 8. Improving Usability and Interactivity 9. Building E-Commerce Sites with WooComerce 10. Troubleshooting WordPress 11. Handling Performance and Maintenance 12. Improving Site Security 13. Promoting and Monetizing the Site 14. Other Books You May Enjoy Appendix

Creating a custom posts list template

The default blog page shows all the posts on your site using the standard design of the theme. Sometimes, we want to display a set of selected posts inside a page as a grid with a customized design to promote them. We can use shortcode inside a page or create a page template to provide this functionality.

In this recipe, we are going to create a page template that will display a list of posts in a grid-based design.

Getting ready

Open the code editor and make sure you have access to the theme files in your local or external WordPress installation. Also, you need to add featured images to a few of the existing posts in order to see the complete design of Post Grid in action.

How to do it...

Follow these steps to create a custom page template that will display a list of posts as a grid:

  1. Open the wp-content/themes/twentytwentychild folder using a file manager.
  2. Create a new template called post-grid.php.
  3. Add the following code to the post-grid.php file, define it as a template, and save the changes:
<?php /* Template Name: Post Grid */ ?>
  1. 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));
?>
  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(); ?>
  1. 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;
}
  1. Log in to the site as an administrator.
  2. Click the Posts menu,
  3. Click the Add New button to create a new post.
  1. 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:
  1. Click the Publish button to create the post.
  2. Follow steps 8 to 11 and create two more posts called Grid 2 and Grid 3.
  3. Click the Pages menu.
  4. Click the Add New button to create a new page.
  5. Add a title for the page and select Post Grid as the template under the Page Attributes | Template settings.
  6. 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.

How it works...

Let's identify how the template code works by using the following steps:

  1. First, we call the get_header function to include the default header for the template.
  2. Then, we add the Template Name: Post Grid comment to the post-grid.php file. Once this is added, it will be available for selection in the Page Attributes | Template setting section of the page edit screen, even without any template code.
  3. Next, we add the header and the query for retrieving posts. We did this in Step 5. In this scenario, we are loading all the published normal posts in the site.
  4. Then, we use the have_posts function on $post_list to check if any posts are being returned from the query. Once results are found, we traverse through the resultset using a while loop and add the post-related information inside an unordered list.
  1. We use the built -in get_the_post_thumbnail_url, the_permalink, and the_title functions to retrieve the featured post image URL, the link of the post, and the title.
  2. Next, we use the wp_reset_postdata function to restore the loop back to the main query of the post or page. Adding this function is essential to preventing conflicts in data loading in the main query after our secondary query has been executed.
This function should be invoked when we have a list of results from our query. Placing this outside the if statement may reset the main query, thus creating conflicts in the page.
  1. Next, we added the get_footer function to add the default footer and complete the page template.
  2. Finally, we added the CSS of the <ul> and <li> tags to make a grid type design with three columns. We used 31% as the width and float:left on the <li> tag to divide the list into three columns. Then, we set width:100% and fixed the height to 200px to make it look similar on all the posts, regardless of the uploaded image size.

Now, you understand how the template code works.

There's more...

In this recipe, we loaded the list of all the normal posts in the site. This is a primary implementation of a post list template. In the real world, these templates are used for displaying custom post types or filtered sets of posts instead of all posts. Let's take a look at the scenarios where we can change the query to make the template much more flexible:

  • Displaying a custom post in a list template: We can modify the query to display a list of entries from a custom post type such as WooCommerce products by changingpost_type:
$post_list = new WP_Query(array('post_type'=>'product', 'post_status'=>'publish', 'posts_per_page'=>-1));
  • Displaying posts from a specific category: We can modify the query to display posts only from the category specified in the category_name parameter:
$post_list = new WP_Query(array('post_type'=>'post', 'post_status'=>'publish', 'category_name' => 'books', 'posts_per_page'=>-1));
  • Displaying posts with more than x number of comments: We can modify the query to display a list of posts that have more than 10 comments:
$post_list = new WP_Query(array('post_type'=>'post', 'post_status'=>'publish', 'comment_count' => array( 'value' => 10,   'compare' => '>=',    ), 'posts_per_page'=>-1));

The WP_Query class provides a large number of such query parameters, so the possibilities are endless. You can view all the available query parameters at https://developer.wordpress.org/reference/classes/wp_query/.

You have been reading a chapter from
WordPress 5 Cookbook
Published in: Mar 2020
Publisher: Packt
ISBN-13: 9781838986506
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at ₹800/month. Cancel anytime