掌握 WP_Query:10个有用的例子

到目前为止,我们已经学习了 WP_Query 这个类几乎所有相关的知识,是时候尝试一些例子了。在这个部分,我们将在 10 个不同的场景下利用 WP_Query 类及相关的函数。

这是一个有趣的练习,同时我希望它也是非常有教学效果的。让我们开始吧!

注:由于时间精力有限,本教程没办法翻译分享,希望朋友们可以加入我们,帮助我们进行翻译,有小酬谢,有意者请联系倡萌QQ 745722006(注明:教程翻译)。

以下为原文:http://code.tutsplus.com/tutorials/mastering-wp_query-10-useful-examples–cms-22980

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 Reminder on Creating a Loop With WP_Query

Just to make this article be understandable separately from the “Mastering WP_Query” series, I should do a nano-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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
 
if ( have_posts() ) {
 
    while ( have_posts() ) {
 
        the_post();
 
        // Post data goes here.
 
    }
 
}
 
?>

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?php
 
$args = array(
    'category_name' => 'news',
    'posts_per_page' => 3
);
 
$my_query = new WP_Query( $args );
 
if ( $my_query->have_posts() ) {
 
    while ( $my_query->have_posts() ) {
 
        $my_query->the_post();
 
        // Post data goes here.
 
    }
 
}
 
// Reset the `$post` data to the current post in main query.
wp_reset_postdata();
 
?>

Let’s see the difference between the two:

  • 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: 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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
 
// Get the year we're in.
$current_year = date( 'Y' );
 
// Setup arguments.
$args = array(
    // Get the author with the nicename "john".
    'author' => 'john',
    // Get his posts from this year.
    'year'   => $current_year
);
 
// Instantiate new query instance.
$my_query = new WP_Query( $args );
 
?>

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
 
// Get the current post id.
$current_post_id = get_the_ID();
 
// Get the current post's category (first one if there's more than one).
$current_post_cats = get_the_category();
$current_post_first_cat_id = $current_post_cats[ 0 ]->term_id;
 
// Setup arguments.
$args = array(
    // Get category's posts.
    'cat' => $current_post_first_cat_id,
    // Exclude current post.
    'post__not_in' => array( $current_post_id )
);
 
// Instantiate new query instance.
$my_query = new WP_Query( $args );
 
?>

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:

1
2
3
4
5
6
7
8
9
10
11
12
<?php
 
// Setup arguments.
$args = array(
    // Order by comment count.
    'orderby' => 'comment_count'
);
 
// Instantiate new query instance.
$my_query = new WP_Query( $args );
 
?>

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
 
// Setup arguments.
$args = array(
    // Get the "slider" post type.
    'post_type' => 'slider',
    // Get a specific slider category.
    'category_name' => 'home-slides',
    // Get all slides and don't paginate.
    'nopaging' => true
);
 
// Instantiate new query instance.
$my_query = new WP_Query( $args );
 
?>

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?php
 
/* 
 * Create new post type called "Quotes"
 * (refer to the `register_post_type` function to
 * learn more about creating custom post types).
 */
function quote_post_type() {
 
    $args = array(
        'label' => 'Quotes',
        'public' => true
    );
 
    register_post_type( 'quotes', $args );
}
 
add_action( 'init', 'quote_post_type' );
 
// Setup arguments.
$args = array(
    // Get the "quotes" psot type.
    'post_type' => 'quotes',
    // Randomize the order.
    'orderby' => 'rand',
    // Get only one item.
    'posts_per_page' => 1,
);
 
// Instantiate new query instance.
$my_query = new WP_Query( $args );
 
?>

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 e-commerce 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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?php
 
// Source: http://scribu.net/wordpress/advanced-metadata-queries.html
 
// Setup arguments.
$args = array(
    // Get the "product" post type.
    'post_type' => 'product',
    // Setup the "meta query".
    'meta_query' => array(
        array(
            // Get the "price" custom field.
            'key' => 'price',
            // Set the price values.
            'value' => array( 100, 200 ),
            // Set the compare operator.
            'compare' => 'BETWEEN',
            // Only look at numeric fields.
            'type' => 'numeric',
        )
    )
);
 
// Instantiate new query instance.
$my_query = new WP_Query( $args );
 
?>

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<?php
 
/*
 * Usage:
 *
 * [embed_post slug="my-post"]
 * [embed_post slug="my-post" full="false"]
 * [embed_post type="movie" slug="inception"]
 */
 
function tutsplus_embedded_post_shortcode( $attributes ) {
 
    // Extract shortcode attributes.
    extract(
        shortcode_atts(
            array(
                'type' => 'post',
                'slug' => '',
                'full' => true
            ),
            $attributes
        )
    );
 
    // Setup arguments.
    $args = array(
        // Get post type ("post" by default).
        'post_type' => $type,
        // Get post by slug.
        'name' => $slug
    );
 
    // Instantiate new query instance.
    $my_query = new WP_Query( $args );
 
    // Check that we have query results.
    if ( $my_query->have_posts() ) {
 
        // Begin generating markup.
        $output = '<section class="embedded-post">';
 
        // Start looping over the query results.
        while ( $my_query->have_posts() ) {
 
            $my_query->the_post();
 
            // Add title to output.
            $output .= '<h2 class="embedded-post-title">';
                $output .= get_the_title();
            $output .= '</h2>';
 
            // Get full post if `$full` is true, otherwise, show the get excerpt
            if ( 'true' === $full ) {
 
                // Add full content to output.
                $output .= '<div class="embedded-post-content">';
                    $output .= get_the_content();
                $output .= '</div>';
 
            } else {
 
                // Add excerpt to output.
                $output .= '<div class="embedded-post-excerpt">';
                    $output .= get_the_excerpt();
                    $output .= '… <a href="'%20.%20get_permalink()%20.%20'">' . __( 'See full post', 'tutsplus' ) . ' »</a>';
                $output .= '</div>';
 
            }
 
        }
 
        // End generating markup.
        $output .= '</section>';
 
    } else {
 
        // Output message to let user know that no posts were found.
        $output = '<section class="embedded-post-error">';
            $output .= '<p>' . __( 'No posts found.', 'tutsplus' ) . '</p>';
        $output .= '</section>';
 
    }
 
    wp_reset_postdata();
 
    return $output;
 
}
 
add_shortcode( 'embed_post', 'tutsplus_embedded_post_shortcode' );
 
?>

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<?php
 
/*
 * Usage with Excerpts:
 *
 * <?php echo tutsplus_show_drafts(); ?>
 *
 * Usage without Excerpts:
 *
 * <?php echo tutsplus_show_drafts( false ); ?>
 */
 
function tutsplus_show_drafts( $show_excerpts = true ) {
 
    // Setup arguments.
    $args = array(
        'post_status' => 'future',
        'nopaging' => true
    );
 
    // Instantiate new query instance.
    $my_query = new WP_Query( $args );
 
    // Check that we have query results.
    if ( $my_query->have_posts() ) {
 
        // Begin generating markup.
        $output = '<section class="pending-posts">';
 
        // Start looping over the query results.
        while ( $my_query->have_posts() ) {
 
            $my_query->the_post();
 
            // Output draft post title and excerpt (if enabled).
            $output .= '<div class="pending">';
                $output .= '<h3 class="pending-title">' . get_the_title() . '</h3>';
                    $output .= get_the_title();
                $output .= '</h3>';
 
                if ( $show_excerpts ) {
 
                    $output .= '<div class="pending-excerpt">';
                        $output .= get_the_excerpt();
                    $output .= '</div>';
 
                }
 
            $output .= '</div>';
 
        }
 
        // End generating markup.
        $output .= '</section>';
 
    } else {
 
        // Let user know that nothing was found.
        $output = '<section class="drafts-error">';
            $output .= '<p>' . __( 'Nothing found', 'tutsplus' ) . '</p>';
        $output .= '</section>';
 
    }
 
    wp_reset_postdata();
 
    return $output;
 
}
 
?>

Example #9: “Post From a Year Ago Today”

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php
 
// Setup arguments.
$args = array(
    // Day (1 - 31).
    'day' => date( 'j' ),
    // Month (1 - 12).
    'monthnum' => date( 'n' ),
    // Year (minus 1).
    'year' => date( 'Y' ) - 1,
    // Show only one post.
    'posts_per_page' => 1
);
 
// Instantiate new query instance.
$my_query = new WP_Query( $args );
 
?>

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
 
$current_page_id = get_the_ID();
 
// Setup arguments.
$args = array(
    // Get children of current page.
    'parent' => $current_page_id,
    // Disable pagination.
    'nopaging' => true
);
 
// Instantiate new query instance.
$my_query = new WP_Query( $args );
 
?>

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!