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. How to output custom the file field values on another page with the file download link
  2. Looking for the ability to authorize a credit collection/token on pre sale products
  3. How to automatically activate the plugin while wordpress first installation using docker
  4. How do I perform an IF/ELSE statement using data from a database on wordpress?
  5. How to check if a post or property has been viewed (on each session)
  6. wordpress How do I remove post_ID from user_meta array value
  7. Wordpress hooks working on dashboard but not on actual website
  8. Form echo is not applied of first item in a list
  9. How can I remove unwanted 1px space under navigation bar?
  10. slow down jump to anchor in divi theme

WordPress problems we are working on

  1. Advice on resolving HTTP 500 on WP site?
  2. Copying plugins to base wordpress image, Plugins folders are visible in cmd but not visible in volume mount
  3. how to handel submitted gravity form which contains singel file
  4. How to rearrange WordPress REST API comments?
  5. how to select multi button at same time with different group? [on hold]
  6. WordPress add access for users to edit his comments
  7. Show directories and files in wordpress uploads folder
  8. Insert date and time to custom wordpress mysql table using input type date and input type time by php code
  9. Contact 7 form is causing error in my website afrter updated to the latest wordpress 5.0
  10. How to Add Javascript Code to Button to track the Clicks in Wordpress

Resolved issues

  1. how to print a variable javascript in a onmousedown event?
  2. Contact form 7 WordPress plugin not showing sender email
  3. Does Wordpress list all pages for crawlers?
  4. How to update links on a WordPress website from Google Drive automatically after changing hosts?
  5. some product thumbnails doesn't show up
  6. How to keep the same page for different languages
  7. WordPress : Treat value in functions.php for all inner PHP files
  8. How to echo something after header tag (wordpress)?
  9. Error layout Elementor Wordpress (not load)
  10. APIProjectMapError when using WP Google Map plugin to display map
wppotion - powered by persistence and passion