April 3, 2017
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:
<?php $args = array( 'post_type' => 'meal', 'category_name' => 'Salads', 'order' => 'ASC' ); $the_query = new WP_Query($args); ?>
From there you can create a new
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; ?>
if 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
The Series So Far
Leave a reply
Part of the How to Code HTML to WordPress collection