In this post, i’ll show you how to create your own new WP_Query & custom loop.
Your new WP_Query will fetch specific posts from your database based on the parameters you add to the code and display them in a new custom loop.
You can then output the list anywhere using a variety of methods, one of which is get_template_part() in a custom function.
Here’s the final result using a few lines of CSS to style the output.
WP Query Parameters
The code in this tutorial, includes 3 parameters:
'orderby' => 'comment_count', 'posts_per_page' => 3, 'post__not_in' => $sticky
- The 1st parameter orders the posts by comment count displaying the most commented post first.
- The 2nd parameter determines how many posts to display in the list which is 3.
- The 3rd parameter excludes any sticky posts from the list.
- Create a new file named wpsites.php using a code editor like Notepad++ and copy & paste the PHP code from the Gist labelled wpsites.php into the new file then upload it to your child themes root directory.
- Copy the code from the view raw link in the Gist labelled functions.php and paste it at the end of your child themes functions.php file.
- Copy the CSS code from the Gist labelled style.css and paste it at the end of your child themes style.css file before the start of your Media Queries section.
The custom function is very simple and includes a conditional tag to limit the display of your posts to single posts only and a hook for positioning the display after the entry content.
The function also includes get_template_part which loads the wpsites.php file based on the conditional tag and hook. You can also reuse the code in the wpsites.php file directly in files or other custom functions.