WordPress wp_query or how to customize the loop


As you may know WordPress uses loop mechanism to find and output content to the pages of your website. It is based on URLs which determine what to pass into the loop. If you are browsing category page, then depending on the number of the articles per page, that loop will generate an output for you. In many cases however, the site owners need a custom wordpress loop.

Standard wordpress loop

In this tutorial we will learn how to work with the_query and customize its default behavior in order to fit our needs. Now let’s look at the default structure of the loop and explain what it does:

if ( have_posts() ) :

      while ( have_posts() ) : the_post();

        // some content

      endwhile;

      else :

        // fallback message

endif;

The above piece of code says “If there are matched posts, then loop through them and display some parameters. They could be titles of the post, their content, dates, authors and so on. If there is no match, then display the following fallback message. The structure is pretty simple and self explanatory.

The real magic happens within the while statement and this is the place where will apply customisation to achieve our goal.

Custom wordpress loop

Now let’s start with the real work and customize the default loop and then output some additional content at the front end. The solution explained below will be applied to the theme files we created in the article named How to create WordPress theme from scratch, but the customized loop can be used with any other theme.

Preparation:

  • Create a new file named front-page.php and place it in the root folder of your theme.
  • Copy the content of index.php and paste it inside the newly created file
  • Right below the following line
<p><?php _e('Sorry, no posts matched your criteria.'); ?></p><?php endif; ?>

paste this piece of code :

<div class="left">

<?php

$catPosts = new WP_Query('cat=3&posts_per_page=2');

if ( $catPosts ->have_posts() ) :

   while ($catPosts->have_posts() ) : $catPosts->the_post(); ?>

        <li><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>

      

    <?php  endwhile;

   else :

        // fallback message

endif;

wp_reset_postdata(); ?>




</div>
  • Save the file
  • Open your css file and paste the following code inside it
.left {float: left;padding-left: 20px;}

.left li {list-style-type: none;}

What the custom loop does

Our customized loop code starts right after the else statement of the main loop which says “no posts are found”. There we open a new div tag that surrounds our customized loop. We do this because we want to control the output easily and give it some simple styling.

After the div that we start a new instance of WP_Query. The object will be stored in a new variable called $catPosts. At the same time we pass  some arguments to our new instance. They are cat for category and posts_per_page which is equal to 2. Looking more carefully at the code you will see that cat is equal to 3. This is the category ID which I previously took from my test WordPress instance. To find the correct ID of your application login to wp-admin section -> Categories -> Click Edit option of the category you want to display content from and look at the URL in the browser. There you will see string that says tag_ID= and then a number. In order for the customized code to work properly in your case, get that ID and replace the number in my example.

The rest of the code literally says : If we have posts in our variable to loop through, then loop through then and display their titles making sure the are active links with titles.

When the loop is finished, we put endwhile and then else statement for the cases where we do not have any posts to loop through. After that we use wp_reset_postdata to reset the data we get from our custom loop. We do this in order not to disrupt the main WordPress query.

Styling and advanced customisation

The styling of our loop is also easy to understand. The whole content is surrounded by div class called left. It pulls the content to the left and gives is padding from the left. Note that each one of the iterations appears in li tags. In this particular case I used list-style-type: none; to remove the bullets.

Now if you followed the steps in this article you would see the two most recent articles from the selected category are the bottom of the like as shown on the following screen shot

Wordpress wp_query or how to customize the Loop

WordPress wp_query or how to customize the Loop

A few additional words regarding  how to customize the loop:

  • Make sure the HTML elements are separated from PHP code. As you can see in out example, we drop out from PHP just before li elements and continue right after the closing tag.
  • In this tutorial we used just two arguments, but WP_Query accepts much more. For example, you may include a category or exclude it using – symbol. The same applies for authors, tags, taxonomy and so on.
  • Arrays are also allowed. You can easily combine 2 or more categories, authors, post types or tags. Here is one example:
$args = array(

            'post_status' => 'any',

            'post_type'   => 'attachment'

);

$query = new WP_Query( $args );

In this additional example the arguments are defined in an array which is later passed to WP_Query. If we need to apply this approach, then our example would look like as follows:

<div class="left">

<?php

$args = array (

'cat' =>3,

'posts_per_page' =>2,

);

$catPosts = new WP_Query($args);

if ( $catPosts ->have_posts() ) :

            while ($catPosts->have_posts() ) : $catPosts->the_post(); ?>

        <li><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>

      

    <?php  endwhile;

            else :

        // fallback message

endif;

wp_reset_postdata(); ?>

</div>


Do you want to share your opinion?

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


*

We are not industry specific. We are WordPress specific. We work with everyone to help them find solutions with their troubles.
If you show us the problem you are experiencing, we will show you how to fix it. It is that simple.


Reported WordPress issues

  1. Add class to body if IP or browser is Danish [duplicate]
  2. Wordpress 5.1.1 conflict with multiple-content-blocks
  3. Get reviews from booking api
  4. Wordpress - Filter relative taxonomy in custom post type
  5. Customising ACF options page values on save
  6. If function on submission contact form 7 (Wordpress) [on hold]
  7. In CodeIgniter, How to access the folder that's outside of application folder using site_url
  8. WordPress UltimateMember reset password URL
  9. How to display the last page when I visit the website in wordpress
  10. How to set / within local wordpress applications to reference the application not http://localhost

WordPress problems we are working on

  1. Why does using my home page shows robot.txt (WordPress)?
  2. WordPress : “Warning: Illegal string” after a PHP upgrade to PHP7.2 [duplicate]
  3. WordPress 125% duplicates widgets / Change Media breakpoints
  4. wp_mail use WordPress's default email template for sending email
  5. Why does [post_thumb] only output the image source instead of the image itself?
  6. single-{custom} page not rendering/printing or being picked up by Wordpress
  7. Single image pages - product images doesn't show after importing products
  8. Deletion of categories but not items on wordpress
  9. Posting Comments to WordPress with WPAPI
  10. In WordPress it is clear that the comments plugin has been placed inside the element's framework. Why is it displayed outside?

Resolved issues

  1. Disable MailChimp popup from Mobile
  2. retrieving HTTP Post request from JobAdder
  3. Wordpress Replace Pagination with Numbers
  4. Issues creating custom post, wordpress plugin
  5. Embedding the thumbnails Youtube Videos (php) Wordpress
  6. Get elements by class name and change class name
  7. Bitbucket Pipeline with AWS EB and Wordpress
  8. International website setup with mulitple languages (WordPress)
  9. Redirect custom Wordpress post
  10. Easiest Backend Platform to Use a Product Configurator
wppotion - powered by persistence and passion