Main loop

MDB main loop

Author: Dawid Adach

-

Main loop

Currently, our blog posts are static, it's a plain HTML which is useless. We want our theme to display a new post as soon as it get's created in WordPress editor. Before we will start rewriting main part (index.php) we will have to add featured image support to our theme.

  1. Add the following code to the functions.php after the last function which we created (and before closing ?> tag).
  2. 
    /**
     * Setup Theme
     */
    function mdbtheme_setup() {
        // Add featured image support
        add_theme_support('post-thumbnails');
    }
    add_action('after_setup_theme', 'mdbtheme_setup');
    
  3. Replace following code in index.php (lines from 55 to 233)
  4. ...
    <!--Grid row-->
    <div class="row wow fadeIn">
    .
    [lines 57-231]
    .
    </div>
    <!--Grid row-->
    ...
    
  5. With the one below:
  6. <!--Grid row-->
    <div class="row wow fadeIn">
    <?php
    if ( have_posts() ) {
    $counter = 1;
    while ( have_posts() ) {
    the_post();
    ?>
    
        <!--Grid column-->
        <div class="col-lg-4 col-md-12 mb-4">
            <!--Featured image-->
            <div class="view overlay hm-white-slight rounded z-depth-2 mb-4">
                <?php the_post_thumbnail( 'medium-large', array( 'class'=> 'img-fluid')); ?>
                <a href="<?php echo get_permalink() ?>">
                    <div class="mask"></div>
                </a>
            </div>
    
            <!--Excerpt-->
            <a href="" class="pink-text">
                <h6 class="mb-3 mt-4">
                    <i class="fa fa-bolt"></i>
                    <strong> <?php the_category(', '); ?></strong>
                </h6>
            </a>
            <h4 class="mb-3 font-weight-bold dark-grey-text">
                <strong><?php the_title(); ?></strong>
            </h4>
            <p>by
                <a href="<?php echo get_permalink() ?>" class="font-weight-bold dark-grey-text"><?php get_the_author(); ?></a>, <?php echo get_the_date(); ?></p>
            <p class="grey-text"><?php the_excerpt(); ?></p>
            <a href="<?php echo get_permalink() ?>" class="btn btn-info btn-rounded btn-md">Read more</a>
        </div>
        <!--Grid column-->
    
      <?php
      if ($counter % 3 == 0) { 
      ?>
      </div>
      <!--Grid row-->
      <!--Grid dynamic row-->
      <div class="row wow fadeIn">
      <?php
      }
      $counter++;                  
      } // end while
      } // end if
      ?>
      </div>
      <!--Grid row-->
    
    

    (Note: if you are not sure which line to replace you can download lesson files at the bottom of the page.)

  7. In your WordPress Admin Panel, navigate to Posts and add 3 new posts. If you want to add a thumbnail to the post, click at "Set featured image" in the right bottom panel:
  8. Setting featured image
  9. Open your blog. You should see your newly created posts with images:
  10. Blog preview

We have used a lot of new functions, let's analyze them one by one:

New functions

if (have_posts()) {...} - this condition checks if there are any existing post to be displayed.

while (have_posts()) {...} - this construction is beginning of WP loop. It will loop through all posts and print code between {} brackets for each post. This is the most basic loop function in next tutorials you will find more advanced loops including conditions and filters.

the_post() - this WP function retrieves the next post, this allows us to use functions below (they won't work without it)

get_permalink() - returns permalink (url) of post.

the_title() - displays post title.

the_author() - displays author name and link to his profile.

echo get_the_date() - prints (echo()) date of post publication.

the_post_thumbnail( 'full', array( 'class'=> 'img-fluid z-depth-2'));() - this function generate feature image code (<img src= .... >) wchich displays feature image assigned to post. it usses 'full' size which we have defined in the previous lesson. It also adds specific classes 'img-fluid z-depth-2' to generated image.

the_excerpt() - display the post excerpt.

Nothing changed? That's perfect! Although we haven't changed anything in the way our website look, we've just made the first step to make our website dynamic. In next lessons you will learn how to create different pages like a single post page, category page or search result page. Imagine that without extracting navbar code to separate file we would have to keep a copy of exactly the same code in multiple places. This is very, very bad and it's against one of the main IT rule - reusability.

Reusability is the use of existing assets. It's very important to write your code in the way it could be used in different places. Exactly same as we did with our navbar. Now we can easily add navbar to different pages (using function require_once();. Shall we change anything in the navbar (i.e. add a new link, or change hyperlink) we will only have to do it once in navbar.inc.php file and change will be automatically reflected in all pages.

Since our navbar is extracted you can have a look at MDB Dropdowns, Icons and other components from documentation to adjust it to your need. In future lessons, we will write a function which will automatically create navbar from WordPress admin panel.

Note

It's a good practice give files which are included inside another a .inc.php extension. This will inform other developers that this file isn't a standalone file but subpart used in other files. Some people tend to use the only .inc extension, however that can be dangerous. When a visitor tries to open .php file server renders it first and show only output. In case of .inc files, a server will show the whole source code of the file.

Let's move to the next lesson where we will learn how to display new posts automatically.


Previous lesson Download Live preview Next lesson

Spread the word:
Do you need help?: Use our support forum

About author

Dawid Adach
For more than 5 years Dawid worked as an IT Consultant specializing in SOA/EAI/ESB in the banking domain. He gained experience working in countries like Netherlands, Belgium, Poland and India developing enterprise-class systems for the most prestigious companies. Since co-founding mdbootstrap.com & brandflow.net in 2016 he has been using and teaching technologies such as Angular, TypeScript, PHP, AJAX, Mongo, SQL, Hadoop Stack, Virtualization, Automation and many others...