Andy from Webcrunch

Subscribe for email updates:

Portrait of Andy Leverenz
Andy Leverenz

April 3, 2017

Last updated November 5, 2023

How to Code HTML to WordPress - Part 6

Part 6 continues my series titled "How to Code HTML to WordPress". In this video, I finish up coding the custom post type feature for the menu section of the page.

How I query the database in WordPress

Querying the database takes place using the WP_Query class available from WordPress. This class allows you to query the database outside of the base loop found on the blog template of most WordPress sites. Using this class allows you to pull only the bits of content you would like to by passing in arguments to the class definition.

This is done like the example below:


$args = array(
    'post_type' => 'meal',
    'category_name' => 'Salads',
    'order' => 'ASC'

$the_query = new WP_Query($args); ?>

From there you can create a new if and while loop that will duplicate whatever content you pass:

<?php if($the_query->have_posts()) : ?>
<?php while($the_query->have_posts()) : $the_query->the_post(); ?>

   <?php the_content(); ?>

 <?php endwhile; ?>
 <?php wp_reset_postdata(); ?>
 <?php else: ?>
     <p><?php _e('Sorry, no meals match your criteria.')</p>
 <?php endif; ?>

Theif loop checks first to see if any data exists. The while loop then loops through any data that does. If no data is present then the contents within the else statement gets printed to the page.

Going forward I repeat this process for each new menu category. Be sure to remember the wp_reset_postadata() function after the while loop otherwise you could run into problems retriving the correct data.

Want to follow along? Download the code

How to Code HTML to WordPress - Start
How to Code HTML to WordPress - End

The Series So Far

Link this article
Est. reading time: 2 minutes
Stats: 741 views



Part of the How to Code HTML to WordPress collection