Context Includes

Context Includes

Oct 14th in Wordpress by Harley

The great thing about WordPress is that it doesn't limit how content is displayed, but provides a 'framework' of ways to do so. Even better, it's possible to change the display according to the content. When writing this tutorial it was hard to explain what's going on... But the best way is this: the post will be displayed within the loop according to its content - or contextual differences. Either way, it's including specific files that match up to the category of the post.

PG

Author: Harley

I'm Harley! I like to call myself a jQueryfied WordPress designer! What a mouthful, huh? I'm based in Australia and have been working with (X)HTML/CSS, Flash, Illustrator and Photoshop for over 3 years, and have found a now year and a half old obsession with WordPress and jQuery. Be sure to get some more info on me on my site!

Preface

This tutorial assumes that you have a WordPress engine running on a server that you have access to upload files, download files and browse to. If you want to run a local server on your computer with a wordpress installation, there is a tutorial on that here for Windows, and here for OS X.

Let me describe a little further in depth what we'll be doing. Many WordPress sites are more than just a blog these days. For those that integrate a Blog, a News System, and a Portfolio, there are many ways to distinguish between each of these posts. For a start, the amount of meta information WordPress attaches to each post is monumental. Dates, Categories, Custom Fields, Options, Tags, amount of tags, etc. It goes on. By picking on one of these, you can manipulate WordPress to display certain things even when the context changes (I.e. different category name, different tag, etc). The method I'm about to teach figures out when a certain category is attached to a certain post, and then bring in a different file accordingly. Contextually! If the context is of a blog, display it like a blog post! If the context is of a portfolio item, display it like a portfolio item! So on, so forth. You get it. Let's go!

Step 1 - Basic Theme Necessities

I've prepared a couple of files; style.css, index.php and some images (thanks TUTs sites!). We'll be building off these to create our final product. Download them, and place the folder in the wp-content/themes folder. Now go to the WordPress Dashboard, click 'design' or 'presentation' if you're still living in the stone age, and select the 'Context Files' theme. Great! Now it's activated we can dive into editing the files and getting on with the tutorial.

Step 2 - the WordPress Posts

For the method to work, a group of posts need to have a certain category. For this, I gave a few of them the category 'Blog', some 'theirNews', and left the rest to be the portfolio group, without any specific category. Make sure to do this, or your results wont be too varied. So make sure your posts (for this tutorial at least) are grouped in some way. It's vital!

Step 3 - WordPress Code

The functional way to describe what happens, is depending on the category, a specific file is included for the loop's code. The heirarchy looks like this:

A Blog post will end up looking like this:

A News item will display like this:

And all other posts, or portfolio items will resemble this:

Notice the little watermarks in the top right of each post? That's proof our system will work!

Anyway. Between the body tags, we need a header and a loop. Add this:

<div id="header">
    <h1><a href="<?php bloginfo('url'); ?>" title="Home"><?php bloginfo('name'); ?></a></h1>
    <p class="description"><?php bloginfo('description'); ?></p>
</div>
<div id="content">
    <?php if(have_posts()) : while(have_posts()) : the_post();
    	
    	//Getting the category and checking it against certain
    	//values to include the correct file goes here...
    	
    endwhile;
    endif; ?>
</div>

Next up, we need to get the category for each post. This uses some Custom WordPress/PHP syntax. Usually you could use get_the_category for the value, but you can get ANY category information via this method (goes under or replaces the comment in PHP):

foreach((get_the_category()) as $category){
    $categoryName = $category->cat_name.'';
}

Now with that, we need to check this value against a value. If you named your categories 'Blog' or 'theirNews', we can now check the $categoryName variable against exactly those names/values. Remember this is in the loop, so this check is made for each individual post.

if($categoryName == 'Blog'){ include(TEMPLATEPATH.'/blogTemplate.php'); }
elseif($categoryName == 'theirNews'){ include(TEMPLATEPATH.'/newsTemplate.php'); }
else(include(TEMPLATEPATH.'/portfolioTemplate.php'));

Each line of the 3 above is relatively the same. The PHP '==' means 'is equal to'. It's two ='s because when using only one = defines a variable. Not what we want. If, elseif, and else are a few conditional PHP tags. You can use multiple elseif statements if you wish to have more than three files!

With the PHP done, we can now create the actual files that are included above. What's interesting about this template is that you can keep the entire loop, category, and includes all within one set of PHP tags. Efficiency!

blogTemplate.php

These files are basically what goes in the loop, consisting of loop template tags. So we can assign each category with the top right watermark, a different class is applied to each different category file. Otherwise, this is all basic WordPress stuff. Create a new file called 'blogTemplate.php' in the theme folder, and fill it up with some PHP goodness!

<div class="post blog">
<h2><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></h2>
<p class="postInfo">Posted by <?php the_author(); ?> | Filed under <?php the_category(' & '); ?></p>
<?php the_content(''); ?>
<p class="postMetaData">
	<a href="<?php the_permalink(); ?>">Read More</a> |
	<?php comments_popup_link('Comments(0)','Comments(1)','Comments(%)'); ?> | 
	<?php the_time('F d, Y'); ?>
</p>
</div>

Just one thing to note. I know it's very bad practice for SEO reasons, but the_content('') has the 2 's so that no 'read more' is displayed. The 'Read More' link in the postMetaData makes up for this!

newsTemplate.php

This is pretty minimalistic. The header is smaller too!

<div class="post news">
<h3><?php the_title(); ?></h3>
<?php the_content(''); ?>
<p class="postMetaData"><a href="#">Visit Source</a> | <?php the_time('F d, Y'); ?></p>
</div>

portFolio.php

Finally, the last sub template file.

<div class="post portfolio">
<img src="<?php bloginfo('template_directory'); ?>/images/portfolio.png" alt="" />
<h2><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></h2>
<?php the_content(''); ?>
<p class="postMetaData"><a href="<?php the_permalink(); ?>">View Project</a></p>
</div>

And that's all the PHP/HTML you'll be needing! If you load your WordPress page, it'll now resemble something like below:

Note you can already see the differences in each post!

Step 4 - CSS

Now to make it pretty! We'll start off with some defaulting code. This is to set it to a base look, get rid of stuff we don't want and style general tags (i.e. headers, etc).

a{
	text-decoration: none;
	color: #b93a00;
}

*{
	margin: 0;
	padding: 0;
}

body{
	background: #000;
	color: #5b5b5b;
	font-family: "Lucida Grande", Lucida, Verdana, sans-serif;
	font-size: 75%;
}

h1, h2, h3, h1 a, h2 a, h3 a{
	font-family:"Trebuchet MS", Arial, Helvetica;
	color: #fff;
	letter-spacing: -2px;
	text-decoration: none;
}

h1 a:hover, h2 a:hover, h3 a:hover{
	color: #8b8b8b;
}

h2{
	font-size: 35px;
	margin-bottom: 10px;
}

h3{
	font-size: 20px;
	color: #a8a8a8;
	letter-spacing: -1px;
	padding-bottom: 20px;
}

Now we need some structure to our page.

#wrapper{
	margin: 0 auto;
	width: 500px;
	font-size: 11px;
}

#header{
	height: 150px;
	font-family: Georgia, 'Times New Roman', Times, serif;
	border-bottom: 1px solid;
	border-color: #222;
}

#content{
	padding-top: 20px;
}

.post{
	margin-bottom: 40px;
	min-height: 150px;
}

Next we'll add the little blackground watermarks in:

.blog{
	background: url(images/blogbg.png) no-repeat top right;
}

.portfolio{
	background: url(images/portfoliobg.png) no-repeat top right;
	min-height: 150px;
}

.news{
	background: url(images/newsbg.png) no-repeat top right;
	padding-right: 100px;
}

Our theme is taking shape! All that's left is some image styling and the styling of the postMetaData!

#header h1{
	font-size: 50px;
	padding-top: 30px;
}

#header p.description{
	font-style: italic;
	font-size: 16px;
}

.post img{
	float: left;
	padding-right: 10px;
	padding-bottom: 20px;
	
}

.post p{
	padding-bottom: 15px;
}

.postInfo{
	padding: 10px;
}

.postMetaData{
	padding: 10px;
	background: #141414;
	margin: 10px 0;
	width: 480px;
	display: block;
	clear: both;
}

.postMetaData a{
	color: #06f;
}

The last section of code needed, your theme should now look complete! This tutorial teaches you a couple of things. A versitile way to get category info, how to use this in conjunction with conditional tags, and grouping PHP!

Final

You Also Might Like...

Leopard With jQuery

Adding to Our Leopard Desktop with jQuery

in Javascript / AJAX by Harley

Last Week I got you all to create a neat looking Dashboard/Desktop. You guys are gonna totally FLIP when you hear what’s in this jam packed tutorial! More focus on the Dashboard (I swear it’s cooler than it sounds, and requires a lot of code), and I’ll even go into how to create a stack (seperate from the dock, sorry jqDock doesn’t like nestled <ul>s), and some extra little bits to make it all click.

Continue Reading

jQuery Dashboard

Leopard Desktop with jQuery using jqDock

in Javascript / AJAX by Harley

jQuery adds a whole lot of cool functionality to your websites. It can do a range of things, from animation to AJAX. It’s usually frowned upon to rely heavily on jQuery to design your sites, but it’s fun to go wild every now and then. In this tutorial I’ll teach you how to use jQuery to create a completely coded Dashboard, just like Leopard! This can be handy in hiding a whole lot of gadgets or widgets you don’t have space for!

Continue Reading

5 Time-Saving CSSEDIT TIPS

5 Time Saving CSSEdit Tips

in HTML / CSS by Harley

CSSEdit is another fantastic web dev app, which takes Apple’s WebKit by the reigns to deliver a fantastic real-time visual CSS editing experience. But that’s just it! People only know it as a visual CSS editor, when it is actually much more! I use these 5 fantastic tips to keep my work flow fast and smooth.

Continue Reading

The Power of WordPress

Build a Newspaper Theme With WP_Query and the 960 CSS Framework

in Working with CMS's by Harley

WP_Query is a powerful tool to control what comes out of your loop. Today I’m going to teach you all how to use it to make a 3 columned newspaper theme that has all your main blog posts in the main column, and off to the side a set of posts with a certain category. We’ll be using the 960 CSS framework for the basic layout and reset of our theme, it will chop a lot of work off what’s needed!

Continue Reading


  • Subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.


Related Posts

Check out some more great tutorials and articles that you might like

Enjoy this Post?

Your vote will help us grow this site and provide even more awesomeness

Plus Members

Source Files, Bonus Tutorials and
More for $9 a month for all TUTS+
sites in one subscription.

Join Now

User Comments

( ADD YOURS )
  1. PG

    BroOf October 14th

    Ouh Cool!

    ( Reply )
  2. PG

    insic October 14th

    Awesome tutorial!

    ( Reply )
  3. PG

    Simon October 14th

    You could easily simplify this by using in_category().

    ( Reply )
  4. PG

    Phoat October 14th

    Simon is right. You could use in_category() and include only those elements that are different and do away with the various includes, however, having separate files makes everything nice and organized.

    Great tutorial!

    ( Reply )
  5. PG

    Roshan October 14th

    Nice tips. Thanks.

    Roshan
    http://www.instantshift.com

    ( Reply )
  6. PG

    Dan Harper October 14th

    I use something similar to this for a lot of my WordPress themes. Although I use if in_category() like Simon said.

    ( Reply )
  7. PG

    MD October 14th

    Great tut :) I’m gonna try it

    ( Reply )
  8. PG

    Lamin Barrow October 14th

    Cool tut. Thanks for all of your time and effort putting it together. :)

    ( Reply )
  9. PG

    Ben Griffiths October 14th

    Great article, thanks :)

    ( Reply )
  10. PG

    Cansado October 14th

    Great but what shoul I do if I want to style a part into the post? For example put some boxes for the documents to PDF with the icon of pdf in the left and a little description below?

    Thanks!

    ( Reply )
  11. PG

    Chris Robinson October 14th

    Great tut! But I agree using in_category() would be a little cleaner but having the seperate template files is a nice way of doing it too.

    I would love to see a tutorial on writing a custom functions.php for a Theme Admin Options page and implementing the custom values into the loop, like setting a featured posts category, setting a stylesheet selector, etc…like a lot of the premium wp themes have.

    ( Reply )
  12. PG

    Tommy M. October 14th

    Awesome! This was just what I was looking for. Thanks.

    ( Reply )
  13. PG

    Kevin Quillen October 14th

    “Great but what shoul I do if I want to style a part into the post? For example put some boxes for the documents to PDF with the icon of pdf in the left and a little description below?”

    You mean adding an icon to links that link to specific file types? I usually reference this excellent page:

    http://www.hunlock.com/blogs/Attach_icons_to_anything_with_CSS.

    ( Reply )
  14. PG

    Long Beach Web Design October 14th

    As usual, another greatly explained tutorial. Thanks!

    Jad Limcaco
    Long Beach Web Design (Jad Graphics)
    http://www.jadgraphics.net

    ( Reply )
  15. PG

    Harley Alexander October 14th

    @Chris Robinson: That’s actually next on my plate. Well done for predicting the future ;)

    ( Reply )
  16. PG

    revy October 14th

    great stuff! I’ve been wanting to try something like this on my site! Gonna give it a try! Thanks!

    ( Reply )
  17. PG

    Afrix October 14th

    Great tut i have to do somthign with it !!

    http://afrix99.deviantart.com/

    ( Reply )
  18. PG

    mark October 14th

    include[_once[require/_once]] are statements and do not require parenthesis. Otherwise, pretty cool

    ( Reply )
  19. PG

    Simon Vallee October 14th

    Nice post – thanks! I think we’ll soon be seeing a lot more blogs include context-sensitive post styles.

    ( Reply )
  20. PG

    Michael Lomas October 15th

    Very nice – I’ve recently started using Wordpress as a CMS – not too much in the way of blogging at the moment but I’m sure I’ll finding this useful when the time comes.

    ( Reply )
  21. PG

    Kevin Quillen October 15th

    Everytime I come back to see new comments its always ‘GREAT TUT LOOKING FORWARD TO MORE’. When will we see real discussion around here?

    ( Reply )
  22. PG

    James October 15th

    Quite a nice tutorial! Thanks harley.

    I’m not too sure on the scalability of this exact implementation though. A custom plugin might be more suited if this were to be integrated into a production site – with a plugin you could manage the styles/css of each new category created within the admin panel, instead of having to fiddling with source…

    ( Reply )
  23. PG

    wut? October 15th

    @kevin quillen

    When there is a link to forums to “discuss” the topic. Comments are comments, not discussion

    ( Reply )
  24. PG

    Kevin Quillen October 16th

    Oh yeah, you’re real clever. Go back to 4chan.

    ( Reply )
  25. PG

    wut? October 16th

    get off your high horse “kev”

    ( Reply )
  26. PG

    kekoa October 16th

    Whoever you are “wut?” can you please not turn the comments into some kind of negative banter. Thanks

    ( Reply )
  27. PG

    dlv October 16th

    great, very nice concept and implementation, thanks for share it
    thanks !

    ( Reply )
  28. PG

    Shane October 18th

    Very interesting tutorial – thanks for exploring.

    ( Reply )
  29. PG

    blog October 19th

    dr-lin – I could build a tumblr clone with this theme :D

    ( Reply )
  30. PG

    Robert October 21st

    This is a fine tutorial that sparks lot of ideas. I do agree with the comments about using in_category() and Chris Robinson’s comment about combining this technique with creating a Theme Options page so that the site admin can set any category ID for the special categories without having to hard-code category names in the code. One can even allow multiple categories in the option by separating them with commas.

    This just shows how powerful and customisable Wordpress is.

    ( Reply )
  31. PG

    Olivier acobs October 27th

    interesting article. Very good explanation of the includes.

    ( Reply )
  32. PG

    Busby November 1st

    Great! Thanks, this is useful

    ( Reply )
  33. PG

    kareem November 23rd

    this is wonderful tutorial i will put acopy of this lesson on
    my site here
    http://www.as7ap4you.com

    ( Reply )
  34. PG

    trinity February 17th

    help!
    Why not work to read more?

    ( Reply )
  35. PG

    Andy August 27th

    Before searching a question, I found the answer!
    I really enjoyed this great tot and great comments as well.

    ( Reply )
  1. Arrow
    Gravatar

    Your Name
    August 27th