Kevin Dench

kevindenchdesign.com

Cutting up Template Files for WordPress

Written by , posted on 05 Oct, 2015

cutting up template files for WordPress can be difficult, follow these few steps to get started.

Introduction

This guide is meant to introduce beginner’s to moving static content over to the WordPress loop. Before beginning this tutorial, please review or read WordPress Workflow: Your First WordPress Site. That will help you build a solid foundation before we get started.

When I start a new website I like to start by building it statically, this includes mobile responsiveness and all the JavaScript I need. After that step is done, and the client is happy with the dummy content and how things interact, I’ll move on to migrating it over to a content management system. Cutting up template files for WordPress is pretty straight forward, so we’ll just cover that one for now.

Getting Started Cutting up Template Files

So let’s assume that by this point you have a completely static site. It’s good practice to take a moment to analyze the layout one more time, before moving on. I personally like to start with the home page when I’m cutting up template files. Let’s take a look at an example:

When cutting up template files, it's important to start somewhere, I like to start with the home page.

 

We have a header block, a left aside, our main content area, and our right aside. On the bottom of the page we have our footer. A good place to start, in my opinion is with the most challenging thing, so it’s downhill after that (hopefully).

Step One: Examine Content for Repetition

The life-blood of WordPress is the loop. So when cutting up template files, we want to keep opportunities for this in mind. As you’re looking through your finished static content — well, finished a relative term — you will want to keep a look out for repetitive content. Things like mock post listings, your navigation, image galleries, and other similar things. The reason is, because you will soon take that repetitive content loop over it using WordPress. Let’s take a look at some hypothetical, repetitive content you might find:

As we look at our main content, while cutting up template files, we can see opportunities for looping code blocks.

Here we can see that we have three repeating blocks of content. We have the container around the content with a border, an image, a content title, the text, and the right arrow. Since this all repeats 3 (or more) times, it makes for a good candidate for the WordPress loop. However, don’t let that term intimidate you, though, when cutting up template files think of the loop as your greatest asset. It means less work for you, because it will basically cut and paste your html structure. Then when you add WordPress template tags like the ones found in posts you’ll feel even more awesome.

Step Two: Looping items

As we are cutting up template files in WordPress we want to dynamically import the title and content of our post

How it works is when you execute a WordPress query and pass in the parameters to restrict it to only the content you’re interested in, it checks the database for your request. Then it returns a StdClass Object of $post objects. If you were to print the array of a $your_query = new WP_Query( $args ); using this method:


echo '<pre>'; 
    print_r($your_query->post); 
echo '</pre>';

You’ll notice the single arrow after the variable name. This is because we’re using a StdClass Object, and we need to get the property of post. If you’re using array format, this will fail with an error similar to cannot get property of non-object. In order to access an array using array format you simply write $your_array['index']. Advanced Custom Fields uses array format.

Anyway, implementing the above code, is a great way to debug things as well as look at your options. So by printing this array like we did above, it’s likely you’d get a group of posts or a single post (depending on your parameters) that prints something like this:


    WP_Post Object
    (
	    [ID] => 574
	    [post_author] => 1
	    [post_date] => 2015-07-22 04:38:10
	    [post_date_gmt] => 2015-07-22 04:38:10
	    [post_content] => Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus commodo ac nunc non tempor. Duis ullamcorper purus in mattis suscipit. Ut in enim non magna fringilla finibus eget feugiat arcu. Nam nec dolor sit amet nisi volutpat convallis. Nullam ac diam eget urna tempus scelerisque eu ac elit. Suspendisse volutpat, orci in aliquam condimentum, nisl ipsum pulvinar sapien, non eleifend risus mi at turpis. Fusce sed fringilla enim, aliquet aliquet urna.

	    Quisque a turpis gravida, dignissim nunc ac, dignissim nulla. Aenean sollicitudin dapibus mi, non malesuada est ultrices vitae. In quis finibus arcu. Phasellus auctor euismod sem auctor dictum. Duis malesuada est vel nibh condimentum euismod. Aliquam erat volutpat. Praesent porta et lorem vehicula iaculis. Nam a erat sit amet arcu elementum finibus at sit amet enim.
	    [post_title] => Test Post 4
	    [post_excerpt] => Duis feugiat lobortis tristique. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Curabitur euismod tempus purus, id commodo nibh faucibus molestie. 
	    [post_status] => publish
	    [comment_status] => open
	    [ping_status] => open
	    [post_password] => 
	    [post_name] => test-post-4
	    [to_ping] => 
	    [pinged] => 
	    [post_modified] => 2015-07-22 04:38:10
	    [post_modified_gmt] => 2015-07-22 04:38:10
	    [post_content_filtered] => 
	    [post_parent] => 0
	    [guid] => http://localhost/websites/Development/wordpress/?p=574
	    [menu_order] => 0
	    [post_type] => post
	    [post_mime_type] => 
	    [comment_count] => 0
	    [filter] => raw
    )

An array like this is what WordPress iterates over. The WordPress function of the_title(); is essentially shorthand for echo $your_query->post->post_title, same with the_content(); function which essentially is like writing this echo $your_query->post->post_content. A lot of times in WordPress if you see get_ in most, if not all cases, it means that’s a function that simply returns the value. Conversely, if you use the_ you’re returning and echoing it. So if you’re trying to store something to a variable you’ll want the get_ method.

So let’s apply what we’ve learned. First, assuming you have some dummy posts in your post type of post, we will initiate our query for that post type:


$args = array (
	'posts_per_page' 	=> 8,
	'post_type' 		=> 'post',
	'orderby' 		=> 'title',
	'order' 		=> 'ASC',
);

$posts_query = new WP_Query( $args );

Great, now that we have our query initiated, we need to output and loop our html structure:


$args = array (
	'posts_per_page' => 8,
	'post_type' => 'post',
	'orderby' => 'title',
	'order' => 'ASC',
);

$posts_query = new WP_Query( $args );

if( $posts_query->have_posts() ) : ?>

	<a id="post-<?php the_ID(); ?>" <?php post_class('post-container'); ?> href="<?php the_permalink(); ?>">

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

			$ACF_img = get_field('ACF_image', $post->ID); ?>

			<img src="<?php echo $ACF_img['url']; ?>" alt="<?php echo $ACF_img['alt']; ?>" title="<?php echo $ACF_img['title']; ?>" />
			<h2><?php the_title(); ?></h2>
			<p><?php the_excerpt(); ?></p>
			<span class="right-arrow pull-right"></span>

		<?php endwhile; ?> 

	</a>

<?php wp_reset_postdata(); endif; ?>

Okay, now let’s go over this line-by-line.

Line 12:
I put the anchor element inside the if-statement, because if there are no posts, I don’t want it to show that at all. I could put an “else” in there that says there are no posts to display, but I opted for a leaner snippet. You’ll also notice some php inside the anchor element. I have an id with the post ID in it, because it’s a handy way to target it. Along that same vein I have the WordPress post_class() function which is a function that spits out a bunch of information about the post in the form of classes. For example, let’s say I wanted all posts tagged as “cooking” to have a light background of cooking wallpaper. I can access that tag class and style it accordingly. However, you may be asking yourself, “that’s great, but what about the styling I worked so hard to setup?” Luckily, that’s easy too. You’ll see how I passed in post-container to the function, and if you have more than one it’s simply: post_class(array('post-container', 'post-item', 'post-awesome'));. Note that I also used the_permalink(); which is a quick way to get the link when you’re inside the loop.
Line 14:
The while-loop. You’ll notice for both the if-statement and the while-loop are using $posts_query->have_posts() this is a necessary piece. Notice that after the while-loop we have something slightly different: $posts_query->the_post() this sets up our postdata for the loop. When we set up postdata we also have to reset it it. You’ll notice we’re doing just that on line 27, before closing the if-statement.
lines 16-21
We use get_field() to store our image array values from Advanced Custom Fields. Since we don’t want it printing we’re using that get_ method we talked about earlier. It’s important to remember those differences when cutting up template files in WordPress. Anyway, we store it in a variable and use array format to access it in the next line. Under that <img> tag, we have the template tags for the title, and the excerpt. Some times the_excerpt() and the_content() can behave strangely when wrapped in paragraph tags. This is because when you’re using the WYSIWYG editor in WordPress it will output the content pre-wrapped in paragraph tags. So just watch out for that.

There you go, when WordPress receives the completed request query, and has looped the HTML, you should start to see the magic happen. If you’re having php errors, let me know in the comments and I’ll see if I can help. If it’s working though, it will loop over the posts and plug in the content in place of the template tags, which makes it a snap. We’ll talk about some other template tags later.

At this point we have simplified our original file quite a bit. Instead of three blocks of static content, we have turned it into one block that gets looped with the_title(); for the title, and the_excerpt(); for the excerpt. Then whatever method we’re using for images (whether we’re using ACF the_field('your_image_for_those_posts'); or the WordPress core function the_post_thumbnail( $size, $attr );) you’ll use that.

Now that we're done looping the main content, we can move on to the next step of cutting up template files in WordPress.

Now our main content is looped, and if we were to visually represent that fact, it would look something like this:

The next step of cutting up template files for WordPress will be to make the headers, footers, and asides dynamic.

Step Three: Moving on to the Header, Footer and Asides

The next step is making your header, footer, and asides dynamic. It will need to basically be a block of code that gets imported at various points in each document we put a certain tag. There are a few different tags, so let’s take a look:

WordPress has some great hooks to help you when cutting up template files, we'll go over some of them here.

Notice how when naming your asides you will want to make it unique. I have named them “aside-lt” for Aside Left and “aside-rt” for Aside Right. This will be set up in the widget areas section of your functions.php file. The rest of the functions are for the header and footer. The wp_head() function is the hook for the header. On your main page you will use get_header() which hooks into wp_head(). You can also define different headers by using slugs. For example naming a file header-special.php will allow you to use get_header("special") as long as the hook is in that header.

These same kinds of rules apply to the wp_footer(), which is a hook. So you’ll want to place that hook before the </body>. Then call it using get_footer().

Step Four: So… what goes into a WordPress header and footer?

You might already have a header and footer, but when cutting up template files for WordPress, you'll want to take the opportunity to add some dynamic things too.

The first thing you will probably notice is the language attributes function inside the html tag. This is for the purpose of defining the markup language. You can optionally pass in html or xhtml to this function to implicitly define it.

Next is the charset for the blog. This displays the encoding for pages and feeds. More than likely this parameter will always echo “UTF-8”, which is the default encoding of WordPress.

Then, in between the html title tags, you’ll notice a function called wp_title(); this is very useful, because this function takes several arguments:


wp_title ( $sep = '»', $display = true, $seplocation = '' )

The above values of each variables are the default values, and they’re all optional.

What’s all that mean? Well, the $sep defines how you want to separate the various items within the page title. It takes a string value. The next one $display and it is a Boolean of whether or not you want to display this value. This is useful if you’re trying to match the wp_title in a function to determine something. The $seplocation is the direction to display the title. You can tell it to put the separator to the left of the title, or to the right of the title.

In the interest of length, I’m just going to skip to the part that says <?php wp_head() ?> This is the hook we talked about. WordPress is going to parse your header file, going through and rendering the HTML via the server. When WordPress sees one of these files, it’s going to that file or files and print it out where you have placed <?php get_header() ?>. You can also use the <?php wp_head() ?> and <?php wp_footer() ?> to place scripts you define in your functions.php file. For example, let’s say you wanted to clean up your header and clean up your footer, and just import all your stylesheets into the header and all the scripts into the footer. Then you would write a function like this:


function wp_head() {
    /**
     * Print stylesheets in the head tag on the front end.
     *
     * @since 1.5.0
     */
    do_action( 'wp_head' );
}

Or, if you wanted to hook into the footer tag, execute this action:


function wp_footer() {
    /**
     * Print scripts or data in the head tag on the front end.
     *
     * @since 1.5.0
     */
    do_action( 'wp_footer' );
}

Oh, but what about the get_template_part() function? This is a really useful function. In it’s essence it gives you the ability to load a piece of re-usable code, like the way each blog post is styled, into a template file. I’m going to steal a quote from the developer.wordpress.org reference site:

Includes the named template part for a theme or if a name is specified then a specialised part will be included. If the theme contains no {slug}.php file then no template will be included.

The template is included using require, not require_once, so you may include the same template part multiple times.

For the $name parameter, if the file is called “{slug}-special.php” then specify “special”.

What this means is a little easier to explain with a picture, plus, I like visuals:

When cutting up cutting up template files for WordPress keep in mind useful functions like get_template_part()

In our example header code, this function will include this file called nav-header.php which contains the navigation for the header. The reason for this is that you may have more than one navigation, and you want to keep them in separate files, so you can import them during different conditions. Well, since WordPress 3.0.0 Thelonious Monk, which is the same version as they introduced custom post types (covered here) — now you can! It’s a very powerful use of WordPress functions. Especially if you create your code to be reusable.

Conclusion

Now you are well on your way to cutting up template files for WordPress. Yes, it can be a little bit challenging and may take some debugging. You will be much better off getting a solid grasp of how the WordPress loop works and how to implement it. This was kind of a narrow guide, because it would be impossible to know exactly how to help your particular case for that WordPress has extremely knowledgeable moderators in the WordPress support forums, for you benefit. If you have questions about cutting up template files, just let me know in the comments and I’ll do my best to answer them. Also, for you more seasoned folks, what are some ways you go through this process? Did I leave anything out? Enjoy!


This was posted under these Tutorial, WordPress categories, under these , , tags.