Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
June 15, 2022 02:26 am

Mastering WP_Query: 10 Useful Examples


Now that we learned almost everything about the WP_Query class, it's time to try out some examples. In this part, we're going to work on 10 different scenarios to utilize the WP_Query class and related functions.


It will be a fun exercise and I hope it will be equally educational. Let's begin!




A Quick Tutorial on Creating a Loop With WP_Query


Just as a refresher, here is a mini-tutorial on creating WordPress loops with the WP_Query class.


It's not different than creating a regular loop, really. A typical WordPress loop goes like this:



And creating a loop with the WP_Query class has only a few differences:



Let's see the differences in the second versin:



  • we set some arguments for our WP_Query instance

  • we instantiated the WP_Query class

  • we added $my_query-> to the beginning of the have_posts() and the_post() functions (so they're now the methods of the WP_Query class)

  • and we reset the data of $post so it can return to the main query


Now we know how to create a loop with WP_Query and the difference between a regular loop and a loop created with WP_Query. We're not going to create loops in every example (for the sake of keeping the tutorial short and on topic), so you can refer to this section if you need to create a loop with the examples below.



Example #1: All an Author's Posts in This Year


Let's say that you want to list a specific author's posts written in the current year in a special Author's Posts This Year section. A simple combination of two WP_Query parameters will suffice:



Pass this query in a loop and you're good to go!



Example #2: Latest Posts From This Category (Except the Current Post)


Let's say that you want to create a loop under each post in their single post pages, and list latest posts from the category that the post is in. Of course, you have to exclude the current post in case it might be one of the latest posts from that category. Here's how you create the query with the 'cat' and 'post__not_in' parameters:



For the loop, I suggest creating three or four columns with post thumbnails above post titles. It will look really nice right under the post and before the comments section.



Example #3: Most Popular Posts Ordered by Comment Count


WordPress doesn't have a built-in post view count system, and plugins that provide this functionality are famous for slowing down the website (because on each post view, the plugins write in the database over and over again to record the view counts). However, there's another kind of measurement to determine which posts are most popular: counting comments. And unlike view counts, comment counts are already in the database—the WP_Query class makes it super easy to order posts by comment count:



See how easy this is? Now imagine creating a custom page template with a loop running this query—a Most Commented Posts page.



Example #4: A Simple Slider Setup


When using WordPress to build corporate websites, portfolios or web magazines, sliders have become a must-have industrial standard. I'm not really a fan of sliders (I think it's bad UX) but the web seems to like it, so I can't just say no to my clients while making websites for them. If they want sliders, I use a simple query using the WP_Query class:



The 'cat' argument can be used to retrieve slides from different categories so you can separate slide groups and use multiple sliders on multiple pages. If you're going to use just one slider in your website, you can delete that line and you're good to go.



Example #5: A Random Quote in the Sidebar


If you're keen on literature or religious, you might want to have some of your favorite quotes in the sidebar—it's not a waste of space if you use the area with purpose. So, if you're going to list a random quote in your sidebar on each page view, you can use the following code snippet to create the post type and use the following query to create a loop in your sidebar:



An easy and elegant solution.



Example #6: Listing Products Between a Price Range


I found this example on Scribu.net and I must say, it might be the best WP_Query trick in this tutorial. It's a bit more technical than the others, too, because it can be applied to a WordPress-powered eCommerce website in this context.


Here's the code snippet you'll use if you want to list items from a custom Product post type and filter the results with the price custom fields:



A big kudos to Silviu-Cristian Burca!



Example #7: A Shortcode to Embed Posts Inside Posts


Here's a fun exercise—and we get to use the Shortcode API too! In this example, we're going to create a shortcode that can embed a post within a post. (I hardly contained myself from naming the shortcode [postception].) In the following code snippet, we create a shortcode function that allows us to embed posts (or any custom post type) and lets us choose whether to show the full post or just an excerpt:




Example #8: List of Current Scheduled Posts (With Optional Excerpts)


Here's an idea: Why don't you display some sneak peeks of your upcoming posts to your visitors? You can use the following function to list your scheduled posts with or without excerpts after the titles:




Example #9: Post From a Year Ago Today


If your blog is older than a year, and your content is timeless (meaning either a person from 2015 and 2025 could find the article relevant), adding a Post From a Year Ago Today section might boost your page views. Here's how you do it:



Use this query to build a loop that displays a single post from yesteryear.



Example #10: Show Children of Current Page


You have nothing other than sub-pages' titles to put inside your Services, Our Works or My Portfolio page? Maybe an intro paragraph, but you're right, those pages are doomed to be placeholders. Still, it's a good idea to place sub-pages in there—maybe a grid with square thumbnails and titles below. Let's see which query we should use when creating such a page template:




Key Points to Remember About WP_Query


The WP_Query class gives you a lot of power while looping through post data on your WordPress website. It comes with plenty of options to help you narrow down the list of posts that you want to output. However, there are a few things that you should keep in mind.



Main Query vs. Secondary Queries


There are two types of queries in WordPress. The first one is run automatically by WordPress when you visit a webpage by analyzing the URL that you want to visit. This is the main query. Keep in mind that the main query might not always be the first query to be executed by WordPress. All other types of queries besides the one created by WordPress based on the requested URL are secondary queries. Examples of secondary queries are the queries that we created in previous sections.



Resetting Data After Running the Query


You should always call the wp_reset_postdata() function after running your custom or secondary query. This function will restore the value of the global $post variable so that it contains information about the main post. In other words, it basically restores the context of template tags from the secondary query loop to the main query loop.


There is another function similar to wp_reset_postdata() called wp_reset_query(). The difference between these two is that the latter function resets the main query to the original main query and then calls wp_reset_postdata().


You will only ever need to call wp_reset_query() if you have used the query_posts() function somewhere in your code. However, you should avoid calling the query_posts() function either within themes or inside plugins as this function will change your main query.



Altering the Main Query


What if you want to make changes to the main query? You should do that by using the pre_get_posts action and then using the is_main_query() method to make sure you are working with the main query. Here is an example:



Here we are using the pre_get_posts hook to execute a function which will prevent posts with specific ids from appearing in search results. You can write variations of the above functions to limit search results to a specific date or category etc.



Wrapping Up


I hope you enjoyed these examples as much as I did while preparing them. I paid special attention to giving varying examples both to be fun and to spark your creativity.


If you thought of better examples while reading these ones, or have questions, don't hesitate to shoot a comment below. And if you liked the article, don't forget to share it with your friends!


In the next part, we'll talk about WP_User_Query, one of the sister classes of WP_Query. See you then!


This post has been updated with contributions from Nitish Kumar. Nitish is a web developer with experience in creating eCommerce websites on various platforms. He spends his free time time working on personal projects that make his everyday life easier or taking long evening walks with friends.



Original Link: https://code.tutsplus.com/tutorials/mastering-wp_query-10-useful-examples--cms-22980

Share this article:    Share on Facebook
View Full Article

TutsPlus - Code

Tuts+ is a site aimed at web developers and designers offering tutorials and articles on technologies, skills and techniques to improve how you design and build websites.

More About this Source Visit TutsPlus - Code