惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

H
Help Net Security
月光博客
月光博客
IT之家
IT之家
B
Blog RSS Feed
T
Tailwind CSS Blog
The GitHub Blog
The GitHub Blog
博客园 - 三生石上(FineUI控件)
MyScale Blog
MyScale Blog
J
Java Code Geeks
Stack Overflow Blog
Stack Overflow Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - Franky
博客园 - 叶小钗
阮一峰的网络日志
阮一峰的网络日志
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
U
Unit 42
博客园_首页
B
Blog
V
V2EX
腾讯CDC
Vercel News
Vercel News
量子位
Microsoft Security Blog
Microsoft Security Blog

Pressable

Pressable Achieves Secure Hosting Alliance Certification | Pressable How Pressable MCP Is Changing The Game For WordPress Agencies: A Live Breakdown With Matt Medeiros And Phill Clapham | Pressable April Product Update: Navigation, Organization, And Efficiency | Pressable White-Label WordPress Hosting For Profitable Agencies | Pressable A Guide To Client Onboarding For WordPress Agencies| Pressable WordPress Plugin Management For Scalable Agencies | Pressable WordPress Maintenance Contracts For Agencies: A Complete Guide | Pressable 6 Essential SOPs For WordPress Agencies | Pressable Pressable MCP: Control Your WordPress Hosting With AI. | Pressable WordPress Hosting Cost: Pricing Tiers And What To Expect | Pressable WordPress Performance Budgets: Setting And Monitoring Goals | Pressable WordPress Automation With No Code Automation Tools | Pressable Implement Single Sign-On (SSO) In WordPress | Pressable How To Build A Real Estate Site On WordPress | Pressable Headless WordPress Showdown: Next.js Vs Gatsby | Pressable How To Automate White-Label WordPress Hosting With WHMCS | Pressable Developer Toolkit Update: Automation & UI Enhancements | Pressable How To Build A DXP Platform With WordPress How To Boost WordPress Agency Client Retention: 4 Strategies White Label WordPress Admin For Agency Clients Performance Testing For WordPress Agency Client Sites Performance Testing For WordPress: A Framework For Agency Client Sites How To Upload A Video To WordPress | Pressable How To Mitigate The Impact Of AI Scraper Bots On WordPress Sites WooCommerce ERP Integration: Automate Your Back Office WordPress Personalization: How To Display Tailored Content To Visitors | Pressable WooCommerce Conversion Rate Optimization: A Data-Driven Approach How To Price Your Online Course: WordPress Monetization Guide 7 Ecommerce KPIs You Should Be Measuring | Pressable WooCommerce Vs. BigCommerce: Which Is Best For Your Business Needs? | Pressable WooCommerce Performance Troubleshooting: Diagnosing Speed Issues Step-by-Step | Pressable
WP_Query: The Pro's Guide To Better WordPress Sites
Pressable · 2019-10-13 · via Pressable

WordPress Logo

Ask Your Favorite AI

Copy the link to a markdown format of this article for ChatGPT, Claude, Gemini, or your favorite AI.

WordPress developers are constantly looking at ways to improve the functionality and performance of their clients’ sites. To aid in this effort, WordPress includes an extensive library of functions that can be used to add features and functionality to a site.

If, for example, you want to grab the title of a blog post within The Loop, which is PHP code that WordPress processes and displays on the current page, you can use the function the_title(). You can similarly use the function the_content() to retrieve the content of a blog post or retrieve post categories using the function get_categories().

Although WordPress has functions for just about everything you could want to do with a site, there will inevitably come a time when you’ll need to perform a task that can’t be handled using WordPress’ built-in functions. Consider, for example, how you might query data coming into the Advanced Custom Fields plugin and return that data for a post. To perform the query in this example, you’d need to look outside of WordPress’ built-in functions. WordPress includes a class that enables you to retrieve information from the WordPress database within The Loop using a custom query with custom parameters. This class is called WP_Query and, as you push further into developing on WordPress, you should become familiar with this valuable tool for developers.

My team and I recently completed a Python to WordPress migration for a client. The project required so many customizations and custom post types that we looked outside of WordPress’ built-in functions to target the exact information that we needed. In this case, the client needed their site to show only current events, meaning that it needed to reference the date that an event would take place.

WordPress includes a function, get_the_date();, which returns the date that an event was created or input. Because this function is limited to the event’s creation date, it would not suffice for our project. We used Advanced Custom Fields to create a custom field that would allow us to track the date that any particular event takes place. Using WP_Query, we were able to write a custom query that pulled events based on the custom event field. The end result was that the site’s visitors could view a list of events that were either currently taking place or were scheduled to take place in the future.

The basic principle of working with WP_Query is to get information from the database in a way that can be looped as though it were retrieved using built-in WordPress functions. An added benefit of writing custom queries using WP_Query is that, by setting up helper functions, you can significantly extend WordPress’ functionality. To give you a taste of WP_Quuery in action, I’ve shared a sample query below based on my team’s recent Python to the WordPress migration project.

$args = array( 
'orderby' => 'date',
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => -1,
);

$the_query = new WP_Query( $args );

if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
the_content();
}
wp_reset_postdata();
} else {
echo '

Sorry, there are no posts to display

You may notice that the query in this example looks a lot like a regular post loop query. The key difference is in the $args array, which allows you to specify the information that the query will pull from the database. Inside the $args, we can pass all sorts of criteria that will alter the outcome of the loop.

Once the query and loop have been set, we need to fill in the $args array so that it passes the correct arguments. If, for example, you wanted to get the custom post type for events that I described in my example, you could use the following arguments:

$args = array( 
    'orderby'        => 'date',
    'post_type'      => 'events',
    'post_status'    => 'publish',
    'posts_per_page' => -1,
);

$the_query = new WP_Query( $args );

With this code, we are telling WordPress to query the database for a post type named events (the custom post type that we created) and only retrieve the events that have a published status. The variable posts_per _page can be used to specify the number of records that will be returned. Leaving it at -1 will return every applicable record.

At this point, we have retrieved the events post type, but we’re not done yet. We still need to process the data so that only the events with dates that are current and/or future will be displayed, and so that events with past dates will be ignored. This functionality can be achieved using the following adjusted query:

$time = current_time( 'timestamp' ); // Get current Unix timestamp

$args = array( 
'post_type' => ‘events',
'post_status' => 'publish',
'posts_per_page' => -1,
'meta_key' => 'start_date',
'meta_value' => $time,
'meta_compare' => '>=',
'orderby' => 'meta_value',
'order' => 'ASC'
);

$the_query new WP_Query( $args );

As before, our query is grabbing the post type of events that are published and returning them all. The magic comes into play when we query the values from Advanced Custom Fields so that we can alter the results.

In this example, the following arguments are used to achieve this functionality:

  • $time: Early in the script, we tied the time that the script loaded to a variable called $time as a Unix timestamp.
  • start_date: We want to target ‘meta_key’ => ‘start_date’. The start_date field, which is set in Advanced Custom Fields, is tied to our custom post type meta_key. We need this field to be able to query the data from Advanced Custom Fields.
  • meta_value: Here we are saying that we are looking for events with start_dates equal to the variable $time that we passed. But this isn’t our desired result as we’re interested in more than just events that are timed for today. We want events listed for today as well as the future. What do we do in this case?
  • meta_compare: The solution lies with meta_compare. We can use it to specify that, when we are looking for the value of meta_key, we want to compare it to something. Here we have >= which means we are looking for events greater than or equal to the value we set in meta_value. This is where WP_Query really shines as it allows us to add functionality that would otherwise be difficult to implement.
  • order: Finally, you can see that we are also able to sort the meta_value in ascending order. This arranges the events a clean chronological order.

My team’s recent Python to WordPress migration project afforded us the opportunity to put the powerful capabilities of WP_Query to good use. When you find yourself in a situation where WordPress’ built-in functions will not allow you to grab the data that you need in the format in which you need it, be sure to use custom queries with WP_Query. Just remember that with great querying comes great responsibility. And don’t forget to reset the post data when you’re done.