Watkins Web 3: Blog

Cheat Sheet: Wordpress Conditional Functions

As we’ve discussed, Wordpress templates control every page of that template type. For example, if you have three categories — News, Features, and Quick Links — the template category.php is going to control the HTML output that results when visiting all three URLs: http://example.com/category/news/, http://example.com/category/features/, and http://example.com/category/quick-links/. Most likely the only difference between those pages will be the text at the top (<h1>Posts categorized as News</h1> vs. <h1>Posts categorized as Features</h1>) and of course the particular posts that get listed as belonging to the category.

This rigid logic is the default for almost every template including single.php, tag.php, category.php, and search.php. However, Wordpress provides a host of conditional functions that let you check to see whether a particular category/tag/page (etc.) is being displayed. You can therefore output additional content, hide content, alter styling by adding classes, etc. It’s up to you.

Category Conditional

Lets use our “Quick Links” category as an example. Suppose we have written our category.php to display our list of posts in the standard way: we just link each post name to its corresponding permalink page (using the_permalink()) so that visitors can read the whole post by clicking on any of those links.

But suppose our “Quick Links” posts consist only of a post title and custom field called link_url that stores the URL of the external page we are linking to; in other words, Quick Links don’t use the main content field at all, so there’s no particular need to view their permalink pages. For Quick Links, we might want the titles to be linked directly to those external websites. Here’s how we might use the is_category() function inside category.php to alter our code:

<?php  
	<h2>Posts categorized as <strong><?php single_cat_title( '', true ); ?></strong></h2>
	<ul class="post-list">
		<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
			if ( is_category( 'Quick Links' ) ) {
				$link_url = get_post_meta($post->ID, 'link_url', true); ?>
				<li><a href="<?php echo $link_url; ?>"><?php the_title(); ?></a></li>
			<?php }
			else { ?>
				<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
			<?php }
			endwhile; else: ?>
		<p>Sorry, no posts matched your criteria.</p>
		<?php endif; ?>
	</ul> <-- /.post-list -->
?>

More Functions

Here are some other common conditional functions along with some examples:

is_page()

Detects whether the URL being displayed is using the page.php template or shows a particular page:

<?php  	
	if ( is_page( 'About' ) ) {
		echo ("This is the about page.");
	 }
	else {
		echo ("This is not the about page.");
	}
?>

is_single()

Detects whether the URL being displayed is using the single.php template or shows a particular post:

<?php  	
	if ( is_single( '12' ) ) {
		echo ("This is the post that has ID 12.");
	 }
	if ( is_single( 'I love Design' ) ) {
		echo ("This is the post that has the title I Love Design.");
	 }
?>

has_tag()

Detects whether the current post has a particular tag. So probably most useful on single.php.

<?php  	
	if ( has_tag( 'web' ) ) {
		echo ("This post is tagged as web.");
	 }
?>

is_tag()

Detects whether the URL being displayed is using the tag.php template, or is a particular tag page:

<?php  	
	if ( is_tag( 'web' ) ) {
		echo ("Now listing posts tagged as web.");
	 }
?>

Further Reading

Cheat Sheet: Wordpress Custom Fields

Wordpress is primarily for blogging, and so the primary fields associated with a post make sense for blogging: title, date, content, excerpt, featured image, categories, and tags.

But very often we are using Wordpress posts for non-blog purposes, such as a design portfolio, a staff directory, or a calendar. In these cases we have to decide how to make use of the standard blog fields. In a design portfolio, we’d probably use title for the name of the project, content for the project description, featured image for the project photo/screenshot, and perhaps tags for the project media type (print, web, animation, etc.), so that visitors could see all the projects of a certain type. But what if we implement a system like this and find we have additional information that don’t neatly fit into the available fields? This is where custom fields come in.

In Wordpress, choose Posts > Add New and click on Screen Options. Tick the Custom Fields checkbox, close Screen Options, and scroll to the bottom of the Post editing screen. Here you’ll see the Custom Fields pane. This pane allows you to add any number of custom fields, each of which must consist of a field Name and a field Value.

Lets say you’re constructing your web design portfolio and in addition to showing the project screenshot and description, you also want to (a) link to the live URL of the project and (b) credit the people you collaborated with. For each project post, you could just add a new paragraph in your project description that contained the link and credit info. But the problem with this technique is that it embeds this information inside a field where it doesn’t really belong. Suppose you wanted to output this “metadata” into a different <div> than the_content(), or if you change your mind and want to insert it before the description. In both those cases you’d have to edit every post in your Wordpress database in order to update all your markup.

Adding a Custom Field So instead, it makes more sense to store your credits and project URL in individual custom fields. This ensures maximum flexibility: if you redesign your site in a few years and alter your theme files to output different markup, you won’t have to manually edit the contents of every project post.

Outputting all custom fields at once

Wordpress provides a simple function called the_meta() which outputs all of your custom fields names and values, with each field wrapped in a list item of an unordered list:

<?php 
	 the_meta();   
?>

which outputs:

<ul class='post-meta'>
<li><span class='post-meta-key'>project_url:</span> http://joescoffeeshop.com</li>
<li><span class='post-meta-key'>project_credits:</span> Collaboration with Cindy Sherman</li>
</ul>

This is fine if you just want to display the names and contents of your custom fields.

Outputting a particular custom field

Sometimes you need more control over your ouput than the_meta() offers. Lets suppose we want to wrap differnt markup around our two custom fields. First we’ll use we’ll use the get_post_meta() function. to output our project credits into an HTML paragraph with a class attached. (Notice that we first check to see if $project_credits exists — this prevents outputting empty <p> tags if a particular post doesn’t have any content in project_credits.)

<?php 
	$project_credits = get_post_meta($post->ID, 'project_credits', true); // pass in project_credits as a string to retrieve the correct custom value
	if ($project_credits) { 
		echo ("<p class=\"credits\">$project_credits</p>";)
	}
?>

which outputs:

<p class="credits">Collaboration with Cindy Sherman.</p>

We want to treat our project_url field differently: lets wrap it in a <a> tag with the link text “View Project” so that visitors can just click those words to be taken to the live URL. As above, we’ll run get_post_meta() and store the returned value, but this time we’ll wrap different HTML around it. Notice also how we turn PHP off and on (inside the if conditional) to make writing our HTML easier:

<?php 
	$project_url = get_post_meta($post->ID, 'project_url', true); // pass in project_credits as a string to retrieve the correct custom value
	if ($project_url) {
		?>
	<p class="project-link"><a href="<?php echo $project_url; ?>"> Visit Project</a><p>
<?php
	} 
?>

which outputs:

<p class="project-link"<a href="http://joescoffeeshop.com">Visit Project</p>

Further Reading

Show and tell

Agent 8 Ball

Agent 8 Ball

The Gamits

The Gamits

David LaChapelle

David LaChapelle

These sites claim to be done in HTML 5 without any use of Flash.

Cheat Sheet: Wordpress Templates

As discussed in class, the PHP files that make up a Wordpress theme do not represent particular URLs or Posts in your database. Instead, they are templates for various page types. For example, single.php controls all permalink pages. Through the use of the Loop and PHP variables, each permalink page contains different content (pulled from the database), but they are formatted and laid out the same way.

Template Overview

Here’s a quick overview are the most important templates that control your site.

single.php

Controls the layout and content of a single post or “permalink” page like http://example.com/blog/i-love-garamond.

index.php

Controls the home page, but only if you visit Settings > Reading and set Front Page Displays to Your Latest Posts. If instead you set the front page to display a static page, index.php will not be used at all.

category.php

Controls category pages like http://example.com/blog/category/essays-about-design.

tag.php

Controls tag pages like http://example.com/blog/tag/typography.

page.php

Controls Wordpress Pages like http://example.com/blog/about/.

search.php

Controls search results pages like http://example.com/blog/?s=paul+rand.

archive.php

Controls date-based pages (usually) like http://example.com/blog/2012/02. This particular behavior is dependent on your URL choices under Settings > Permalinks.

author.php

Controls author pages like http://example.com/blog/author/jsmith.
Most useful for multi-author sites. Note: “authors” are just the public-facing word for “users” in Wordpress.

Custom Templates and Template Hierarchy

You don’t have to make use of every one of the templates listed above. Wordpress has a built-in feature called the “Template Hierarchy” which means that when certain templates are missing from the theme, others will take over to display your content. A good example is archive.php. While archive.php controls date-based browsing of posts, it will be used for category and tag pages if you are missing a category.php or tag.php file.

A related feature enables you to create additional templates that control a specific Page, Category, Tag, etc. I’m calling these “custom templates.”

Let’s use a custom Page template as an example. Suppose we’ve created a few Wordpress pages that are being displayed on our site: About, Contact, and Colophon. The content for each page is of course determined by the content fields in Wordpress, and the layout and HTML is determined by our page.php template. Suppose page.php is designed with a main column and sidebar to match our blog and portfolio. Now suppose we want to post a new page called Birthday Party that has a single main column and no navigation links. The best method would be to duplicate page.php, rename it to page-birthday.php, and edit it. The first change should be to give it a logical Template Name at the top (this also informs Wordpress that this is different from the regular page.php template):

<?php
	/**
	 * Template Name: My Birthday Page
	 *
	 * @package WordPress
	 * @subpackage Starter Kit
	 */ 
 ?>

Page templates Once we’ve added this new file and uploaded it our theme, it becomes available in the Page Attributes pane for any Page. Once we choose it from the Template pop-up and re-publish the Page, our Birthday Party page will use the new template.

Here’s another example. Suppose we have created blog categories called Features, Essays, and Quick Links. As discussed above, category.php will by default control the category listing pages located at http://example.com/blog/category/features/, http://example.com/blog/category/essays/, and http://example.com/blog/category/quick-links/.

But suppose we want to present Quick Links a little differently. First, we figure out the ID number of the Quick Links category (in Wordpress, click Posts > Categories, hover over the category name and look in your browser’s status bar for the ID). If Quick Links turns out to be Category ID number 3, we could then create a new category template called category-3.php. Once uploaded, http://example.com/blog/category/quick-links/ will immediately start using that template. Unlike pages you don’t need to choose the template from within the Wordpress inteface.

Further Reading

Cheat Sheet: Wordpress Image Handling

As we’ve discussed, Wordpress provides two primary ways to use images on your site. First is the Insert into Post method, where your image becomes part of the flow of the content field: you could conceivably use this method dozens of times in a long post, interspersing your text with images wherever they are most relevant.

The second option is using the Featured Image pane, also known as the Post Thumbnail. By assigning an image to the post as the Featured Image, it becomes a post “attachment”. The disadvantage of this method is that you only get to use one image per post, and you can’t insert it into the middle of your content. But the advantage is you have more flexibility when it comes to layout and image customization. For instance, on an archive page you could show that featured image as a small thumbnail image alongside each post title, but on the permalink page that same image could be output at full size at the top of the content area. You can think of the Featured Image as another database field, like the Post’s Title and Category, that happens to contain an image file.

Custom Sizes: Insert Into Post

When you click Upload/Insert in a Post, you can either upload a new image or choose one from the existing Media Library. Once you’ve uploaded/selected your image, you’ll see the various image settings available to you. (Note: in general you’ll want to set Link URL to “None”, unless you particularly want the image to be linked to its full-size version. The other fields are fairly self-explanatory.)

Scroll down to the four Size options: Thumbnail, Medium, Large, and Full Size:

Insert into Post Sizes

When you upload an image, Wordpress automatically generates these three sizes of thumbnails in addition to storing the original image, and before you click Insert Into Post you can decide which image size is most appropriate.

To change these sizes globally, visit Settings > Media and type in new numbers for Thumbnail Size, Medium Size, and Large Size. Note that only Thumbnail allows for the option to crop the image to exact dimensions — Medium and Large preserve the aspect ratio of the original. When you next use Insert into Post, you’ll find your sizes have been updated.

Custom Sizes: Featured Image

It’s important to understand that the Thumbnail/Medium/Large sizes only affect images inserted into the post content. If you click the Medium size option but then click Set as Featured Image, that does not mean the Medium sized image will be used in your template.

Instead, featured image sizes are controlled by settings stored in your functions.php file. Open functions.php and you’ll how it works. The first two lines just set up the ability to add custom sizes, and you can leave them as they are. But the add_image_size settings allow you to create (and give names to) any number of image sizes, and you can choose whether or not they should be cropped. I recommend avoiding the words “Thumbnail”, “Medium”, and “Large” to avoid confusing them with the standardized names used by Insert Into Post.

<?php	// Images, Thumbnails, Thumbnail sizes
	add_theme_support( 'post-thumbnails' );
    set_post_thumbnail_size( 300, 200 ); // default Post Thumbnail dimensions   
	// Add custom sizes
if ( function_exists( 'add_image_size' ) ) {
	add_image_size( 'huge', 1600, 9999 );
	add_image_size( 'normal', 600, 9999);
	add_image_size( 'mini', 50, 50, true );      // true means cropped
	}
?>

This now means you can run the the_post_thumbnail() function and pass in any of your size keywords as the function paramater (though you probably wouldn’t use them all in a series like this):

<?php 
	the_post_thumbnail('normal');	// outputs normal image size (1600 px wide)
	the_post_thumbnail('huge');		// outputs huge image size (600 px wide)
	the_post_thumbnail('mini'); 	// outputs mini image size (50 px by 50px)
?>

So if you want to change these or add an additional size, just add another line to your functions.php file, upload it to your theme, and that new size should now work in your theme templates.

Regenerating Thumbnails

Remember that Wordpress only generates it’s various image sizes and thumbnails at the moment you upload them. If you upload many images and then later change your custom sizes in Settings > Media or functions.php, you will probably have to regenerate your thumbnail images. Fortunately there’s a plugin, called Regenerate Thumbnails, that lets you do this all in one step. Try installing it and running it from Tools > Regen. Thumbnails.

Further Reading