Navigation

14 key WordPress functions to jump-start theme development

By Joe Nyaggah | How To, WordPress | May 31, 2013

After 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.

Share this post
Comments (no login required)
  • Apostolis Taxidaridis

    nice article! what about custom comments ?

  • Michael

    I’d actually recommend the Debug Bar plugin for during any sort of development, as well as any other extensions that people have built for it. However, hiding the admin bar would ruin that completely.

  • Matt Kreiling

    Thanks for this post – I don’t have my snippets in order and this will help. BTW, you mention that you want to name your editor css “tiny-mce-styles.css” and then the snippet uses “editor-style.css”.

    • http://nyaggah.com/ Joe Nyaggah

      Matt, that’s if you want to name your file something else and/or place it inside a directory i.e. not just in the theme root.

      • Matt Kreiling

        I understand, I was just point out a small inconsistency in your post here:
        – 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*’);
        Thanks again.

  • http://illuminea.com Miriam Schwab

    Useful list! Just by the way, you can disable the admin toolbar without adding code to your functions file – just go to your profile and deselect the box that says “Show Toolbar when viewing site.” Voila – it will stop displaying! Want it to reappear? Check the box.

  • harishchouhan

    Thanks for writing this article. Really useful.

  • http://sbcjr.com/ Steven

    Great resources here, thanks for sharing! I create a custom plugin for most of my WP sites to prevent updates from affecting my changes, and it looks like several of these would actually be perfect in that setting as well. Thanks again!

  • Bappy

    No doubt, just Awesome..

  • shamimhsm

    waw. It is a nice post. I like this very much

  • ashish

    nice article

  • Jeremy Smith

    This has prevented me from having loads of frustration when it comes to menu creation when making a completely new theme for a site I am doing. Can’t tell you how happy I am!

  • Maxim Aginsky

    Brief article Joe. Thanks

  • Irfan Abdurrasyid

    great article, very useful..

  • zombi

    Hi!
    how to create left and right sidebar both in one page.

  • Manish

    nice article! use full for me……..

  • Jayanta Dey

    Nice
    post. Came to know lots about WordPress
    theme development. It’s an awesome post. Thank you very much. Keep sharing with
    us.

  • John

    You don’t specify where the hide admin toolbar (during development) code should be placed. This is a major oversight by most web devs, that assumes a level of knowledge of the platform which is above beginner. Most of you guys say “I hardly know anything, and even I can do this” and then you give people a line of code without me knowing where it goes… Should I just paste it anywhere? Maybe in the root folder in a readme.txt? Be specific, or these highly (Googe Ranked) blogs are of no use to me and many like me. To be honest, I was just looking for better function reference than the WP codex. For example, one of the most commonly used functions is poorly documented. They simply say use get_post(); when in fact you need to run it inside a loop for it to work. Very obscure documentation… and during my hunt for a more expanitory function reference, I get articles like this? What am I doing wrong? Is there some magical place on the internet where I can learn this stuff? I’m no dummy. I have strong front end skills, but beginner-mid php skills. Pointers?