14 key WordPress functions to jump-start theme development

Default avatar.
May 31, 2013
14 key WordPress functions to jump-start theme development.

thumbnailAfter a few years (or even months) of designing and developing WordPress themes, especially for clients, you start to realize that a lot of the functionality can be standardized or distilled down into a "starter theme or kit". This helps get the development process started and moving along apace.

The best first step in doing this, I've found, is to nail down most of the common functions and include them in the functions.php. This functions.php file will need to be extended to meet the particular theme's needs as new projects arise, but it will provide a more than awesome starting point for development.

There are about 13 key functions that I like to start out with and will add to them as needed...

1. Custom menu support

The navigation menu feature, introduced in WordPress 3.0, allows for the intuitive creation and maintaining of navigation menus in themes.

At the very least, a standard theme will need a main navigation menu, perhaps in the header and a secondary navigation menu in the footer. To do this, we will register those two menus "Main Menu" and "Secondary Menu"

While this isn't a particularly new feature, its still nice to wrap it in an if function_exists() just in case the user is stuck in a pre 3.0 installation:

In the functions.php file, include the following:

if ( function_exists( 'register_nav_menus' ) ) {
	register_nav_menus(
		array(
		 'main_menu' => __( 'Main Menu', 'cake' ),
		 'secondary_menu' => __( 'Secondary Menu', 'cake' ),
		)
	);
}

Now that the Menus are registered, we need to tell the theme where to output them. We'd like the Main Menu to appear in our header. So, in our header.php file, we include the following code:

<?php if ( has_nav_menu( 'main_menu' ) ) { ?>
	<?php $defaults = array(
	 'theme_location' => 'main_menu',
	 'menu' => '', 
	 'container' => false, 
	 'echo' => true,
	 'fallback_cb' => false,
	 'items_wrap' => '<ul id="%1$s"> %3$s</ul>',
	 'depth' => 0 );
	 wp_nav_menu( $defaults );
	?>
<?php } else { ?>
	<ul>
	 <?php wp_list_pages('title_li='); ?>
	</ul>
<?php } ?>

First, we check to see if we have a menu called 'main_menu' defined and if we do, we insert its contents here, otherwise we fallback to the default wp_list_pages() which we can further customize to display the links as we need.

If you'd like even further customization of the menu, see the WordPress codex page on wp_nav_menu() function.

We want the secondary menu to appear in the footer, so we open up the footer.php and include the following code:

<?php if ( has_nav_menu( 'secondary_menu' ) ) { ?>
	<?php $defaults = array(
	 'theme_location' => 'secondary_menu',
	 'menu' => '', 
	 'container' => false, 
	 'echo' => true,
	 'fallback_cb' => false,
	 'items_wrap' => '<ul id="%1$s"> %3$s</ul>',
	 'depth' => 0 );
	 wp_nav_menu( $defaults );
	?>
<?php } else { ?>
	<ul>
	 <?php wp_list_pages('title_li='); ?>
	</ul>
<?php } ?>

2. Style the visual editor

This function allows you to use custom CSS to style the WordPress TinyMCE visual editor.

Create a CSS file named editor-style.css and paste your styles inside. As a placeholder, I like to start with styles in the editor-style.css file of the Twenty Twelve theme.

In the functions.php add the following:

add_editor_style();

If you don't want to use the name "editor-style" for your CSS file and also want to move the file elsewhere, e.g. in within a css directory, then modify the function.

For example, I want to name my file tiny-mce-styles.css and I want it within my CSS directory; so my function will look like this:

add_editor_style('/css/editor-style.css');

While we're at it, we might as well style the editor for right-to-left languages. In the theme directory, create a CSS file called editor-style-rtl.css and, at the very least, include the following:

html .mceContentBody {
	direction: rtl;
	unicode-bidi: embed;
}
li {
	margin: 0 24px 0 0;
	margin: 0 1.714285714rem 0 0;
}
dl {
	margin: 0 24px;
	margin: 0 1.714285714rem;
}
tr th {
	text-align: right;
}
td {
	padding: 6px 0 6px 10px;
	text-align: right;
}
.wp-caption {
	text-align: right;
}

Again, as a placeholder, the above styles are from the Twenty Twelve theme. Restyle and extend as needed.

3. Custom avatar support

Most people commenting on blogs online have an avatar associated with them. If, however, they don't and you don't particularly like the WordPress default avatar options, you can define your own.

To do so, include the following code in your functions.php:

if ( !function_exists('cake_addgravatar') ) {
	function cake_addgravatar( $avatar_defaults ) {
		$myavatar = get_template_directory_uri() . '/images/avatar.png';
		$avatar_defaults[$myavatar] = 'avatar';
		return $avatar_defaults;
	}
	add_filter( 'avatar_defaults', 'cake_addgravatar' );
}

What we're doing here first, is checking to see if the function exists. If it does, we add a filter that tells WordPress to use our custom defined avatar as the default.

We are telling WordPress to find this avatar in our "images" directory inside the theme directory. Next step, obviously, is to create the image itself and upload it to the "images" folder.

4. Post formats

The post formats feature allows you to customize the style and presentation of posts. As of this writing, there are 9 standardized post formats that users can choose from: aside, gallery, link, image, quote, status, video, audio, and chat. In addition to these, the default "Standard" post format indicates that no post format is specified for the particular post.

To add this functionality to your theme, include the following code in your functions.php, specifying the post formats you'll be taking advantage of. e.g. If you only want the aside, image, link, quote, and status Post Formats, your code should look like this:

add_theme_support( 'post-formats', array( 'aside', 'image', 'link', 'quote', 'status' ) );

5. Featured image function

The featured image function, as the codex explains, allows the author to choose a representative image for Posts, Pages or Custom Post Types.

To enable this functionality, include the following code in your functions.php:

add_theme_support( 'post-thumbnails' );

We could stop there and leave it up to WordPress to define the thumbnail sizes or we could take control and define them ourselves. We'll do the latter, obviously!

Let's say we're running a magazine site where the featured image will appear in at least 3 different sizes. Maybe one large image if the post is featured or is the newest, a medium sized image if its just a post among the rest and a regular size perhaps to appear elsewhere.

We take advantage of the add_image_size() function that instructs WordPress to make a copy of our featured image in our defined sizes.

To do this, we add the following to the functions.php:

// regular size
add_image_size( 'regular', 400, 350, true );

// medium size
add_image_size( 'medium', 650, 500, true );
	
// large thumbnails
add_image_size( 'large', 960, '' );

See how to work with the add_image_size() function to either soft crop or hard crop your images on the WordPress codex page.

6. Attachment display settings

Once we've defined the above image sizes (regular, medium and large) — and since by default WordPress doesn't do it for us — we'll add the ability to select our those image sizes from the Attachment Display Settings interface.

It would be nice if you could, when writing a post, insert the desired size image by selecting it from the dropdown as you normally would for the WordPress default sizes.

To do this, we add the following to our functions.php:

// show custom image sizes on when inserting media
function cake_show_image_sizes($sizes) {
 $sizes['regular'] = __( 'Our Regular Size', 'cake' );
 $sizes['medium'] = __( 'Our Medium Size', 'cake' );
 $sizes['large'] = __( 'Our Large Size', 'cake' );
 return $sizes;
}
add_filter('image_size_names_choose', 'cake_show_image_sizes');

With that in place, we can select our image sizes.

7. Add feed links (instead of old RSS code in head)

This one is simple. If you've been building WordPress themes for a while, you'll remember the days when you had to manually include code to output the RSS feed right in the header.php. This approach is cleaner and relies on the wp_head() action hook to output the necessary code.

In the functions.php file, include the following:

// Adds RSS feed links to for posts and comments.
add_theme_support( 'automatic-feed-links' );

Make sure that you have it in the header.php, right before end of &rgt;/head&lgt;

8. Load text domain

With this function you take the first step towards making your theme available for translation.

Its best to call this function from within the after_setup_theme() action hook i.e. after the setup, registration, and initialization actions of your theme have run.

add_action('after_setup_theme', 'my_theme_setup');
function my_theme_setup(){
 load_theme_textdomain('my_theme', get_template_directory() . '/languages');
}

Now add a directory named 'languages' in your theme directory.

You can learn more about load_theme_textdomain() function on the WordPress codex page.

9. Define content width

Content width is a feature in themes that allows you to set the maximum allowed width for videos, images, and other oEmbed content in a theme.

That means, when you paste that YouTube URL in the editor and WordPress automatically displays the actual video on the front end, that video will not exceed the width you set using the $content_width variable.

if ( ! isset( $content_width ) )
	$content_width = 600;

WordPress also recommends the addition of the following CSS:

.size-auto, 
.size-full,
.size-large,
.size-medium,
.size-thumbnail {
	max-width: 100%;
	height: auto;
}

While this is useful, its a bit heavy handed. It defines the content width for all content. What if you wanted videos of a larger width on pages than in posts and an even larger size in a custom post type? Currently, there is no way to define this. There is however a feature request proposing the inclusion of the $content_width variable into the built-in add_theme_support().

10. Dynamic sidebar

Your typical theme will have at least one sidebar. The code to define the sidebar is pretty straightforward.

Add the following to your functions.php:

if(function_exists('register_sidebar')){
	register_sidebar(array(
		'name' => 'Main Sidebar',
		'before_widget' => '<aside id="%1$s" class="widget %2$s">',
		'after_widget' => '</aside>',
		'before_title' => '<h3>',
		'after_title' => '</h3>',
	));
}

This registers and defines a sidebar named "Main Sidebar" and its HTML markup.

You can learn more about the register_sidebar() function on the WordPress codex page.

You'll routinely find the need to have more than that one sidebar so you can just copy/paste the above code and change the name.

There is also a register_sidebars() function that will allow you to register and define multiple sidebars all at once but it doesn't give you the flexibility of giving each new sidebar a unique name.

11. Custom "more" link format

If you're displaying excerpts of your posts on a blog index page, by default WordPress will show [...] to indicate there's more "after the jump".

You will most likely want to add a "more link" and define how that looks.

To do this we need to add the following code to our functions.php:

function new_excerpt_more($more) {
 global $post;
	return '...<br /><br /><a href="'. get_permalink($post->ID) . '" class="read_more">read more →</a>';
}
add_filter('excerpt_more', 'new_excerpt_more');

This adds an ellipses '...' right after the excerpt and includes a read more link after two break tags. You can rename and style the read_more CSS class for the link as desired.

12. Basic pagination

Each theme might have different pagination needs but it's always safest to start with a nice default functions: previous_posts_link() and next_posts_link().

function cake_content_nav( $nav_id ) {
	global $wp_query;

	if ( $wp_query->max_num_pages > 1 ) : ?>
		<nav id="<?php echo $nav_id; ?>" class="content_nav clearfix">
			<ul>
				<li class="nextPost"><?php previous_posts_link( __( '← newer ', 'cake' ) ); ?></li>
				<li class="prevPost"><?php next_posts_link( __( 'older →', 'cake' ) ); ?></li>
			</ul>					
		</nav>
	<?php endif;
}?>

13. Redirect after theme activation

If you have special instructions in your theme eg. in your theme options page that you'd like the user to see when they first activate the theme, you can use the following function to redirect them there:

if (is_admin() && isset($_GET['activated']) && $pagenow == "themes.php")
	wp_redirect('themes.php?page=themeoptions');

Pay special attention to the wp_redirect() function. Make sure to replace the 'themes.php?page=themeoptions' with the URL of your page.

14. Hide admin bar (during development)

During development, I sometimes find the WordPress admin (tool) bar to be quite distracting.

It's in a fixed position at the top of the window and depending on my layout can cover some elements of the header.

While still designing and developing, I like to hide the admin bar with this handy function.

show_admin_bar( false );

Do you have any favourite functions for jump starting WordPress template development? What functions would you like to see? Let us know in the comments.

Featured image/thumbnail, multi-tool image via Shutterstock.

Joe Nyaggah

Joe Nyaggah runs the independent design consultancy nyaggah.com based in Newport Beach, CA and specializing in brand identity design, web design & development. He also runs wpnom.com which helps theme designers simplify and streamline the WordPress theme design process. Follow Joe on Twitter here: @wpnom

Read Next

15 Best New Fonts, September 2024

Welcome to our roundup of the best new fonts we’ve found on the web in the previous four weeks. In this month’s edition…

3 Essential Design Trends, October 2024

This article is brought to you by Constantino, a renowned company offering premium and affordable website design You…

A Beginner’s Guide to Using BlueSky for Business Success

In today’s fast-paced digital world, businesses are always on the lookout for new ways to connect with their audience.…

The Importance of Title Tags: Tips and Tricks to Optimize for SEO

When it comes to on-page SEO, there’s one element that plays a pivotal role in both search engine rankings and user…

20 Best New Websites, September 2024

We have a mixed bag for you with both minimalist and maximalist designs, and single pagers alongside much bigger, but…

Exciting New Tools for Designers, September 2024

This time around we are aiming to simplify life, with some light and fast analytics, an all-in-one productivity…

3 Essential Design Trends, September 2024

September's web design trends have a fun, fall feeling ... and we love it. See what's trending in website design this…

Crafting Personalized Experiences with AI

Picture this: You open Netflix, and it’s like the platform just knows what you’re in the mood for. Or maybe you’re…

15 Best New Fonts, August 2024

Welcome to August’s roundup of the best fonts we’ve found over the last few weeks. 2024’s trend for flowing curves and…

Turning Rejection into Fuel: Your Guide to Creative Resilience

Rejection sucks. And for some reason, it’s always unexpected, which makes it feel like an ambush. Being creative is…

20 Best New Websites, August 2024

The overarching theme in this selection is simplicity. Minimalism never really goes out of fashion and with good…

Free AI-Website Builder, Scene, Helps With the Worst Part of Site Design

AI website design platform, Scene As we’ve been hearing constantly for the last couple of years, AI will soon replace…