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 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, thir 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 customization to achieve our goal.

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;}

Now let’s go back and see what the above code would do

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.

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.
wppotion - powered by persistence and passion