Estimated Reading Time: 3 min
To create a front page template with the best post views for your WordPress blog, you’ll need to work with a custom page template in your WordPress theme. Here’s how you can do it:
Steps
- Locate Your Theme Folder: Go to your WordPress installation directory, navigate to
wp-content/themes/your-theme-name
. - Create a New File: Create a new PHP file for your custom page template, for example,
template-best-posts.php
. - Add Template Header: At the top of the file, include a comment to define it as a custom template.
- Query Posts by Views: Use WordPress functions to query posts sorted by a custom field or plugin that tracks views (e.g., the “Post Views Counter” plugin).
- Display Posts: Use a loop to display posts.
Here’s a full implementation:
<?php
/*
Template Name: Best Posts Page
*/
get_header(); ?>
<div class="best-posts-container">
<h1>Top Posts</h1>
<div class="posts-list">
<?php
// Check if the Post Views Counter plugin is installed and active
if (function_exists('pvc_get_post_views')) {
// Custom query to get posts sorted by views
$args = array(
'post_type' => 'post',
'posts_per_page' => 10, // Adjust the number of posts to display
'meta_key' => 'post_views_count', // Key used by Post Views Counter
'orderby' => 'meta_value_num',
'order' => 'DESC',
);
$query = new WP_Query($args);
if ($query->have_posts()) :
while ($query->have_posts()) : $query->the_post(); ?>
<div class="post-item">
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p><?php echo get_the_excerpt(); ?></p>
<span>Views: <?php echo pvc_get_post_views(get_the_ID()); ?></span>
</div>
<?php endwhile;
wp_reset_postdata();
else : ?>
<p>No posts found.</p>
<?php endif;
} else {
echo '<p>Post Views Counter plugin is not active. Please install and activate it to track views.</p>';
}
?>
</div>
</div>
<style>
.best-posts-container {
max-width: 800px;
margin: 0 auto;
padding: 20px;
font-family: Arial, sans-serif;
}
.posts-list .post-item {
border-bottom: 1px solid #ccc;
padding: 10px 0;
}
.posts-list .post-item h2 {
margin: 0 0 5px;
}
.posts-list .post-item span {
font-size: 0.9em;
color: #555;
}
</style>
<?php get_footer(); ?>
Key Notes:
- Dependency on Post Views Counter:
- The code assumes you’re using a plugin like Post Views Counter to track and store post views.
- Replace
meta_key
andpvc_get_post_views
with your own logic if you use a custom solution.
- Styling:
- Basic CSS is included for layout, but you can customize it to match your theme.
- Activate the Template:
- Go to your WordPress dashboard, create a new page, and select “Best Posts Page” under “Template” in the Page Attributes section.