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. i can't post from python to my wordpress site by wordpress_xmlrpc i get ExpatError: not well-formed (invalid token): line 1, column 222
  2. Wordpress cronjob every 5 seconds not working
  3. WP get_terms() returns error on admin side
  4. Functions.php file vanished
  5. link according to Wordpress users
  6. Wordpress Image Upload Not Working on Windows Server IIS
  7. nextgen gallery cusom lightbox
  8. How to make a website where users will be taken from another website? [on hold]
  9. EventsCalender get venue URL and organizer name
  10. wordpress pagination category 404 on page 2

WordPress problems we are working on

  1. WordPress Virus
  2. Trying to do an api fetch using id from earlier api fetch
  3. Host 2 different websites in the same EC2 instance and on the same port
  4. React Front End overrides Wordpress
  5. Twig Wordpress Repeater within a repeater
  6. Mailchimp embedded form font colour
  7. Wordpress backend search not working on multisite
  8. Disable back to top for empty link <a href=“#”>
  9. How to change css in php file
  10. How do I disable re-direct after adding a new product on Dokan Vendor Plugin

Resolved issues

  1. Add/edit custom fields in wordpress
  2. How to integrate multistep jquery form in wordpress plugin using https://www.jqueryform.com?
  3. Wordpress/ACF merging multiple fields value to one
  4. Wordpress autologin, database error on multisite
  5. How to capture customer billing and delivery details before adding product to the cart for the first time?
  6. Menu appearing on mobile view in desktop browsers but not on actual mobiles
  7. How to implement canonical attribute to wordpress website without plugin
  8. Create custom Filter in Wp Query
  9. Alternatives to WP-SCSS to compile scss to css without the need of GULP
  10. WordPress Uncaught TypeError: Cannot read property 'top' of undefined showing when i click on nav link?
wppotion - powered by persistence and passion