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

If you want to use multiple loops on a page, the best way to do that is to run "WP_Query" whenever you need 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 adapts to your situation, and to your WordPress theme.

Creating a child theme

First, we are going to create the child theme of twenty sixteen. I'm doing this because I don't 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 the categories, that's what we'll be working on.

Make a copy of the “archive.php” file from the WordPress theme “Twenty Sixteen.” Don't move it, but make a copy of it. 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:

" >

 

 

 

 

 

 ', esc_url (get_permalink ())),' '); ?>

 

 

 

 

 

 

 

 <?php

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

 the_content (sprintf (

 __ ('Continue reading '% s ' ', 'twentysixteen'),

 get_the_title ()

 ));

 

 wp_link_pages (array (

 'before' => ' '. __ ('Pages:', 'twentysixteen'). ' ',

 'after' => ' ',

 'link_before' => ' ',

 'link_after' => '',

 'pagelink' => ' '. __ ('Page', 'twentysixteen'). ' %',

 'separator' => ' , ',

 ));

 ?>

 

 

 

 

 <?php

 edit_post_link (

 sprintf (

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

 __ ('Edit '% s ' ', 'twentysixteen'),

 get_the_title ()

 ),

 ' ',

 ''

 );

 ?>

 

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

Editing the template-part file

The "twenty sixteen" loop shows more than what I need, so I'll edit that code. I just want to show the snippet and not the content, so we're going to remove 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 '% s ' ', 'twentysixteen'),

 get_the_title ()

 ));

 

 wp_link_pages (array (

 'before' => ' '. __ ('Pages:', 'twentysixteen'). ' ',

 'after' => ' ',

 'link_before' => ' ',

 'link_after' => '',

 'pagelink' => ' '. __ ('Page', 'twentysixteen'). ' %',

 'separator' => ' , ',

 ));

 ?>

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

See also How to display recent articles in a specific category

Find this line:

Replace it with this:

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

In the model part, change the line:

', esc_url (get_permalink ())),' '); ?>

Edit the H2 tags for H3:

', esc_url (get_permalink ())),' '); ?>

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

Creating loops

First of all we are going to remove the inclusion of the code for "twenty sixteen" from our "category.php" file, as 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.

In this example, I will display all posts 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 that 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" then adds 1 to the counter if so.

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 articles with that 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 ' Posts tagged with '. $ tag. ' ';

 

 

 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 output will be a final loop on the remaining articles. If this category does not have an article with the “content” tag, then it will display all the articles 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; ?>

This last code rewinds the articles, then executes the loop again. This time, it checks if an article does not have the “content” tag, 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 appearance and to optimize the handling 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 Social Wall extension brings. With the Social Wall plugin, you can create a wall on your website and provide your members with a refreshing way to interact with the community.

Le WordPress Plugin Social Wall allows your users to: share messages with each other, share images, comment on other people's posts, users can like or dislike a message, they can choose to display the wall only for logged-in users or for all users, admins can delete posts or user comments etc.

Download | Demo | Web hosting

2. Flipkart Affiliate Plus

Flipkart Affiliate Plus is a WordPress Plugin module that connects your WordPress website to the Flipkart Affiliate API. 

Ce WordPress Plugin It makes it very easy to import product data from Flipkart and update it directly on your website. Flipkart Affiliate Plus is the first WordPress plugin for the official Flipkart API. By using it, you will not need to use a third-party API. You thus benefit fully from your work.

Download | 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, product refunds, content grouping, form tracking, 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 enhanced e-Commerce reports, the ability to study how different devices are used by the same user and how purchases are made, the ability to analyze the products that are reimbursed most often, finally to take corrective action, and more.

Download | 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 fairly technical tutorial. Hope we have been explicit on 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.

...