Skip to Main Content

How to correctly use WP_Query on WordPress

Divi: the easiest WordPress theme to use

Divi: The best WordPress theme of all time!

With over 600.000 downloads, Divi is the most popular WordPress theme in the world. It is complete, easy to use and comes with more than 62 free templates. [Recommended]

I am a big fan of the WP_Query class: I use it on several client websites to retrieve and display data in a personalized way.

If you want to use multiple loops on a page, the best way to do this is to run "WP_Query" every time you have to loop.

But there is one drawback: Whenever WordPress executes a loop, it sends queries to the database, which takes longer and can slow down your website.

In this tutorial, I will show you how to use a query for more than one loop. You can do this with the main query or you can use the same technique with WP_Query.

We will explore 3 aspects:

  • Create a child theme and a template file.
  • Create a template piece for the loop content.
  • Create our loops.

But before we discover together How to Install a WordPress Blog in 7 Steps et How to search, install and activate a WordPress theme on your blog

Then back to why we are here.

What you need

To follow this tutorial, you will need:

  • From a WordPress installation for development (locally).
  • A code editor.
  • Articles in your website with multiple categories assigned
  • the twenty sixteen theme of WordPress
  • A child theme of twenty sixteen installed and activated

This technique also fits your situation, and your WordPress theme.

Creating a child theme

First, we will create the child theme of twenty sixteen. I'm doing this because I do not want to change the parent theme.

Discover How to install a WordPress child theme

In your "wp-content / themes" folder, create a new empty folder, which you will call "tutor-theme". You can later choose the name that suits you.

In this folder, create a file called style.css and add the following code:

/*

Theme Name: Tuto Theme

Theme URI: https://blogpascher.com

Description: Theme to support Tutorial on running multiple loops while querying the database just once. Child theme for the Twenty Sixteen theme.

Author: Hervé

Author URI: https://blogpascher.com

Template: twentysixteen

Version: 1.0

*/

@import url ("../twentysixteen/style.css");

Now save this file and activate your new WordPress theme.

The next step is to create a template file for categories, that's what we're going to work on.

Make a copy of the "archive.php" file from the "Twenty Sixteen" WordPress theme. Do not move it, but make a copy. Rename it "category.php".

To go further, discover How to manage WordPress files and folders

This will now be the template file for the categories of your website.

Creating a new template file

The first step is to create a new template file in our theme that will contain a modified version of the "twenty sixteen" loop.

Let's also consult together How to put your WordPress website in Maintenance mode

In the child theme folder, create a subfolder called "includes". And inside, create a new file named "loop-category.php".

Next, open the file "template-parts / content.php" from the parent theme folders (twenty sixteen) and find the following code:

<article id = "post - <? php the_ID (); ?> "<? Php post_class (); ? >>

<header class = "entry-header">

<? php if (is_sticky () && is_home () &&! is_paged ()):?>

<span class = "sticky-post"> <? php _e ('Featured', 'twentysixteen'); ?> </ Span>

<? php endif; ?>

<? php the_title (sprintf ('<h2 class = "entry-title"> <a href="%s »rel="bookmark">' esc_url (get_permalink ())), '</a> </ h2 > '); ?>

</ header> <! - .entry-header ->

<? php twentysixteen_excerpt (); ?>

<? php twentysixteen_post_thumbnail (); ?>

<div class = "entry-content">

<? Php

/ * translators:% s: Name of current post * /

the_content (sprintf (

__ ('Continue reading <span class =' ​​screen-reader-text '>'% s '</ span>', 'twentysixteen'),

get_the_title ()

));

wp_link_pages (array (

'before' => '<div class = "page-links"> <span class = "page-links-title">'. __ ('Pages:', 'twentysixteen'). </ Span> ',

'after' => '</ div>',

'link_before' => '<span>',

'link_after' => '</ span>',

Easily create your website with Elementor

Elementor allows you to easily create any website design with a professional look. Stop paying expensive for what you can do yourself. [Free]

'pagelink' => '<span class = "screen-reader-text">'. __ ('Page', 'twentysixteen'). '</ span>%',

'separator' => '<span class = "screen-reader-text">, </ span>',

));

?>

</ div> <! - .entry-content ->

<footer class = "entry-footer">

<? php twentysixteen_entry_meta (); ?>

<? Php

edit_post_link (

sprintf (

/ * translators:% s: Name of current post * /

__ ('Edit <span class = "screen-reader-text"> "% s" </ span>', 'twentysixteen'),

get_the_title ()

),

'<span class = "edit-link">',

</ Span> '

);

?>

</ footer> <! - .entry-footer ->

</ article> <! - #post - ## ->

Copy this code into the new "loop-category.php" file of the child theme.

Editing the template-part file

The "twenty sixteen" loop displays more than I need, so I'm going to modify this code. I just want to show the snippet and not the content, so we'll delete the content.

What is the difference between H1 and the SEO title of a WordPress article? Find out by consulting this article.

In your new loop-category.php file, find this code and delete it:

<div class = "entry-content">

<? Php

/ * translators:% s: Name of current post * /

the_content (sprintf (

__ ('Continue reading <span class =' ​​screen-reader-text '>'% s '</ span>', 'twentysixteen'),

get_the_title ()

));

wp_link_pages (array (

'before' => '<div class = "page-links"> <span class = "page-links-title">'. __ ('Pages:', 'twentysixteen'). </ Span> ',

'after' => '</ div>',

'link_before' => '<span>',

'link_after' => '</ span>',

'pagelink' => '<span class = "screen-reader-text">'. __ ('Page', 'twentysixteen'). '</ span>%',

'separator' => '<span class = "screen-reader-text">, </ span>',

));

?>

</ div> <! - .entry-content ->

The other step is to replace the "twenty_sixteen_excerpt ()" function with the "the_excerpt ()" function, because the twenty sixteen version does not provide a link to the full article.

See also How to display recent articles in a specific category

Find this line:

<? Php twenty_sixteen_excerpt (); ?>

Replace it with this:

<? Php the_excerpt (); ?>

We also need to make some changes to the title tags.

In the model part, change the line:

<? php the_title (sprintf ('<h2 class = "entry-title"> <a href="%s »rel="bookmark">' esc_url (get_permalink ())), '</a> </ h2 > '); ?>

Edit the H2 tags for H3:

<? php the_title (sprintf ('<h3 class = "entry-title"> <a href="%s »rel="bookmark">' esc_url (get_permalink ())), '</a> </ h3 > '); ?>

Register your model. Then go back to your category.php file we will continue with it.

Creating loops

First we will remove the inclusion of the code "twenty sixteen" from our file "category.php" because we will need to use the new file.

In your category.php file find this code:

get_template_part ('template-parts / content', get_post_format ());

And delete the.

Then we will create the loops.

Are you looking for the best WordPress themes and plugins?

Download the best plugins and WordPress themes on Envato and easily create your website. Already more than 49.720.000 downloads. [EXCLUSIVE]

In this example, I will display all articles with the tag "content", using the conditional tag "has_tag ()". This means that I will have to go through three loops:

  • The first check if the query has posted items with this tag.
  • If so, the second displays the articles with this label.
  • A third displays articles without this tag.

Between each loop, I will use rewind_posts () to rewind messages without resetting the query: we always work with the main query each time.

The first loop: Verification of articles

In your "category.php" file, find the beginning of the loop:

While (have_posts ()): the_post ();

Above this line, define a new variable called $ count:

$ Count = 0;

Then, inside this loop, add this code:

// check if there are any posts with the »tag

$ tag = 'content';

if (has_tag ($ tag)) {

$ count + = 1;

}

This code checks if the messages have the label "content" and then adds 1 to the counter if yes.

The inside of the loop will be similar to this:

// Check for posts in the first loop.

$ Count = 0;

While (have_posts ()): the_post ();

// check if there are any posts with the »tag

$ tag = 'content';

if (has_tag ($ tag)) {

$ count + = 1;

}

endwhile;

The second loop: Restore articles with the tag

The next step is to loop to display items with this tag, only if there are any.

For example, if the value of $ count is greater than 0.

See also How to customize the WordPress dashboard for a client

Add this condition to the loop:

if ($ count> 0) {

rewind_posts ();

echo '<h2> Posts tagged with'. $ tag. </ H2> ';

While (have_posts ()): the_post ();

if (has_tag ($ tag)) {

get_template_part ('includes / loop', 'category');

}

// End the loop.

endwhile;

}

This code verifies that $ count is greater than zero and if so, rewinds the items and runs the loop again. For each item it checks if it owns our label and, if so, it calls the part of the template we just created.

The third loop: View the rest of the articles

The exit will be a final loop on the remaining items. If this category does not have an article with the tag "content", then it will show all items in the category.

Learn as well How to create a multi-author blog and allow your readers to post articles on your blog

In your second loop, add this:

rewind_posts ();

// Second Loop - posts not with the 'content' tag

While (have_posts ()): the_post ();

if (! has_tag ($ tag)) {

get_template_part ('includes / loop', 'category');

}

// End the loop.

endwhile; ?>

Easily create your Online Store

Download free WooCommerce, the best e-commerce plugins to sell your physical and digital products on WordPress. [Recommended]

This last code rewinds the items and then runs the loop again. This time, it checks if an article does not have the label "content" then, it displays the content in the "template-part".

We also suggest you to discover How to add an article printing option to WordPress

You can now test the articles page of your blog. Remember that you can change the filters. In this tutorial we used "content" as a label filter, but you can use the one of your choice.

Discover also some premium WordPress plugins

You can use other WordPress plugins to give a modern look and optimize the grip of your blog or website.

We offer you here some premium WordPress plugins that will help you do that.

1. Social Wall Addon for UserPro

UserPro can be a lot more fun with a social wall. This is what its extension Social Wall brings. With the Social Wall extension, you can create a wall on your website and offer your members a refreshing way to interact with the community.

The WordPress Social Wall plugin allows your users to: share messages between them, share images, comment on other people's posts, users may like or dislike a message, they can choose to display the wall only for users users logged in or for all users, administrators can delete posts or comments from users, etc.

Download in French | Demo | Web hosting

2. Flipkart Affiliate Plus

Flipkart Affiliate Plus is a modular WordPress plugin that connects your WordPress website to the Flipkart Affiliate API.

This WordPress plugin makes it easy to import product data from Flipkart and updates it directly to your website. Flipkart Affiliate Plus is the first WordPress plugin for Flipkart's official API. By using it, you will not need to use a third-party API. You benefit fully from your work.

Download in French | Demo | Web hosting

3. Actionable Google Analytics for WooCommerce

Actionable Google Analytics is a WordPress plugin that allows you to use some of the best features of Universal Analytics, including: Enhanced Ecommerce and User ID Tracking. In addition, this plugin supports the anonymization of IP addresses, the reimbursement of products, the grouping of content, the tracking of forms, etc ...

By using this WordPress plugin, you will save time in the integration of complex Google Analytics code, so you can focus on managing your data.

Its main features are: quick and easy installation, access to 9 improved e-Commerce reports, the possibility of studying how different devices are used by the same user and how purchases are made, the ability to analyze the products that are repaid more often, finally to take remedial action, and more.

Download in French | Demo | Web hosting

Other recommended resources

We also invite you to consult the resources below to go further in the grip and control of your website and blog.

Conclusion

Here ! That's all for this pretty technical tutorial. I hope we have been explicit about how to properly use WP_Query on WordPress. feel free to share the tip with your friends on your social networks.

However, you will also be able to consult our resources, if you need more elements to carry out your projects of creation of Internet sites, by consulting our guide on the WordPress blog creation.

But in the meantime, tell us about your Comments and suggestions in the dedicated section.

...

This article features 7 comments

  1. ___________ ________ _____ ____________
    | Article 1 | | arti 2 | | _A3_ | | |
    | __________ | | _______ | _____ | Article 6 |
    ______________________ | 5 | | |
    | _________ 4 _________ | | ____ | | ___________ |

  2. Hello Blair,
    I thank you for these tutos perfais,
    I would like to ask for a little help please.
    I create my own theme wordpres (html / css) and I have a problem I will try to develop: I plan to create a site similar to msn.com my site will be divided into several divisions (sections ) which are: news, entertainment, health, lifestyle ... etc. that is to say that I wish to realize a first group of Article, and a second group, a third ... etc. but show all groups on the same page and each group belong to a category (niche). I wonder if this wordpress back office can manage the content of each topic separately? with the wordpress loop // Post Content sorry, no posts found! I get a mix of items:
    that is to say that my last written article is placed directly on the first section which is news, while it is an article that belong to lifestyle for example.
    I came across this page https://codex.wordpress.org/fr:La_Boucle I think the multiple loops part can solve my problem!
    I hope you understand what I'm trying to say

    In advance, thank you for your answer,
    Sincerely,

    1. Hello,
      I think you're complicating the task for nothing. Already what I understand is that you want to organize your articles into categories (heading) and each topic can belong to a niche, which can be parent categories. Yes the loop can help you do it, and it's impressive in its simplicity.
      Bravery !

      1. Bonjour.
        first of all thank you for your quick response. I think the theme I just created is no longer compatible with wordpress and that's where the problem comes from.
        in fact since your comments do not support the attached image I will explain by drawing:
        Here is one of the categories of the site
        ___________ ________ _____ ____________
        | Article 1 | | arti 2 | | _A3_ | | | so imagine that each article is
        | __________ | | _______ | _____ | Article 6 | represented by a tile; so we have 6
        ______________________ | 5 | | | articles (each tile contains the image
        | _________ 4 _________ | | ____ | | ___________ | and the title of a particular article)

        My real problem, Mr. Blair, is that I can not complete my articles so that they can move from the 1 tile to the 6 tile, that is to say that when I add a new article and that I publish it I want the latter to take the place of the article 1 as in all the existing themes.
        - I think it's unrealizable since each post (article) has its own properties such as location, height, width ... etc, what do you think then?
        of course the idea is a bit unclear with this scheme, otherwise if I do not bother you and you would like to help me, you have my e-mail (you only have to send an e-mail containing your name).

        Thank you again for your rethink

        1. Good evening, in this particular case, you will need to jump with variables of type "int", so, each time the loop loop, you increment the variable and depending on the value of the variable, you can change the display of the article. For example :

          If ($ i == 1) {
          // your code here
          } Else if ($ i == 2) {
          // the same
          }
          $ I ++;

          Unfortunately, I can not personally assist you at this time.

  3. [...] In this tutorial, I'll teach you how to use WP_Query queries more efficiently on WordPress. [...]

Leave a comment

Your email address will not be published. Required fields are marked with *

This site uses Akismet to reduce unwanted. Learn more about how your comments data is used.

Back To Top
0 shares
Share
tweet
Save