WP Query: Reusable Boilerplate Text

WP Query is the perfect solution for creating reusable boilerplate text for your site without the need of a separate plugin. To oversimplify WP Query allows you to customize your theme using the power of the WordPress Loop without editing it directly. WP Query is a Class Reference that provides access to retrieve information from the database.

The WP Query code sample

// The Query
$the_query = new WP_Query( array( 'name' => 'boilerplate' ) );

// The Loop
if ( $the_query->have_posts() ) {

 while ( $the_query->have_posts() ) {

  $the_query->the_post();

  echo '
'; echo '' . get_the_title() . ''; the_content(); echo '
'; } /* Restore original Post Data */ wp_reset_postdata(); } else { // no posts found }

Setting the Variable

To begin lets set $the_query variable to look for a post with the slug name “boilerplate” this will require you to create a new post with that precise slug name. Feel free to change it as you see fit.

Creating the Loop

This second portion of the code checks if your variable has retrieved a post. If a post is found the while portion continues where HTML is echoed around the templates tags get_the_title() and the_content() which retrieve the title and content from your post respectively. Lastly wp_reset_postdata() completes the process and closes the loop so it doesn’t interfere with anything else that may be running on the page.

Final Step

add the code to template files such as single.php so that the boilerplate post text is automatically added to your posts at whatever place you choose to add the code.

WP Query Boilerplate example
An example of the boilerplate post in action within a child theme based on Twenty Seventeen.