Easily Customize WordPress’ Default Functionality

Advertisement

The absolute best thing about WordPress is how flexible it is. Don’t like the theme? Just change it. Need added functionality? There is probably a plugin you can download or buy. If not, build it yourself! You can change pretty much anything about WordPress. In this article, we’ll go over some easy ways to customize WordPress that you might not know about.

featured-image

Change The Default Source Of jQuery

Another great thing about WordPress is that it comes locked and loaded with all kinds of JavaScript libraries, including jQuery. It also gives you the power to change the source of those libraries according to your needs.

Let’s say we want to relieve our server of some stress by switching WordPress’ version of jQuery for a hosted solution (or CDN version). We can very easily change the source of jQuery with this function:

function add_scripts() {
    wp_deregister_script( 'jquery' );
    wp_register_script( 'jquery', 'http://code.jquery.com/jquery-1.7.1.min.js');
    wp_enqueue_script( 'jquery' );
}

add_action('wp_enqueue_scripts', 'add_scripts');

Three things are going on here. First, we’re using wp_deregister_script() to tell WordPress to forget about the version of jQuery currently being used. We then use wp_register_script() to re-register jQuery (as the script name), using jQuery’s own CDN version. Finally, we use wp_enqueue_script() to add jQuery to our theme or plugin.

One thing to note here is that we’re using add_action(), not add_filter(), to add our scripts. Because we’re not making any changes to the content, but instead relying on WordPress to do something in order for our scripts to load, we use an action hook, not a filter hook. Read about both in the WordPress Codex.

Add Image Sizes

We know that WordPress sets a few different sizes for the images we upload. Did you know you can also (relatively easily) set your own image sizes? And all with two simple functions. If we have a custom header image for our posts with dimensions of 760 × 300 pixels, we could make our images upload to that size with this:

add_theme_support( 'post-thumbnails' );
add_image_size( 'post-header', 760, 300, true );

The first function, add_theme_support(), tells WordPress to allow not just for thumbnails, but for featured images and images of new sizes. The second line, add_image_size(), is where we add our new size. This function accepts four arguments: name, width, height and whether to crop the image. WordPress also advises strongly against using certain reserved names (read: do not use them): thumb, thumbnail, medium, large and post-thumbnail.

Once our new size is created, we can add it to the post’s loop to display it to users, like so:

if ( has_post_thumbnail() ){ 
	the_post_thumbnail( 'post-header' ); 
}

This checks to see whether you’ve uploaded an image and made it the post’s featured image. If so, WordPress displays it. You can also get fancy and add a default fallback image.

if ( has_post_thumbnail() ){ 
	the_post_thumbnail( 'post-header' ); 
}else{
	<img src="'. IMAGES .'/default.jpg" alt="Post Header Image" />
}

In this case, if the post has no thumbnail, it falls back to the default image. Hooray, continuity!

Change the Sidebar’s Markup

Registering a sidebar doesn’t take much. All you really need is a name and an ID to make it clear in the admin area:

register_sidebar( array (
	'name' => __( 'Sidebar', 'main-sidebar' ),
	'id' => 'primary-widget-area'
));

WordPress will apply the default markup for us, which we can style as we want. However, we can also add our own markup and style it as we want. I prefer to use divs for sidebar widgets because they are more semantically correct than list items. I also prefer h3 for widget headings because I usually reserve h2 for the blog post’s title. So, with that in mind:

register_sidebar( array (
	'name' => __( 'Sidebar', 'main-sidebar' ),
	'id' => 'primary-widget-area',
	'description' => __( 'The primary widget area', 'wpbp' ),
	'before_widget' => '<div class="widget">',
	'after_widget' => "</div>",
	'before_title' => '<h3 class="widget-title">',
	'after_title' => '</h3>',
) );

This produces a sidebar that looks like this:


The sidebar with markup. Isn’t the Web Developer Toolbar great? (View image.)

Alter The RSS Widget’s Refresh Rate

WordPress’ built-in RSS widget is fantastic, but sometimes it doesn’t update often enough. Luckily, there is a fairly simple solution for that. Just add this code to your functions.php file:

add_filter( 'wp_feed_cache_transient_lifetime', 
   create_function('$a', 'return 600;') );

As you can see, we are using WordPress’ add_filter() function, which accepts a filter hook, callback function and (optional) priority. The wp_feed_cache_transient_lifetime hook handles the feed’s refresh rates. We’re creating our callback function on the fly using PHP’s create_function() function. It is one line, which returns the refresh rate in seconds. Our refresh rate is set to 10 minutes.

Add Content To The RSS Feed

WordPress’ ability to add targeted content to an RSS feed (i.e. content that only your subscribers can see) is especially cool. This could be anything such as ads, a hidden message or value-added content. In the following example, we’ll add a hidden message.

function add_to_feed($content){
   $content .= "<p>Thanks for Subscribing! You're the best ever!</p>";
   return $content;
}

add_filter( "the_content_feed", "add_to_feed" );

Using the filter the_content_feed, which is called only when the feed is created, we use a callback function to append new information to the post’s content. If we looked at our website’s feed in Google Reader, we’d see this:

Here's our super-secret message to all subscribers.
Here’s our super-secret message to all subscribers. (View image.)

Highlight The Author’s Comments

One fairly common practice is to set off the author’s comments from the comments of readers. I do it on my blog:

My blog hasn't seen a whole lot of activity lately.
My blog hasn’t seen a whole lot of activity lately. (View image.)

So, how do we accomplish this? I’m glad you asked! See, in a pre-2.7 world, some custom coding was required to determine whether the author’s ID matches the commenter’s. On my blog, I just used to check whether the commenter’s ID was 1, which was the ID of the admin. Not very good I know, but I was young and naive (as well as the blog’s only author).

Version 2.7+ has a fancy little function named wp_list_comments, which prints a post’s comments for us. Even better, it applies the class .bypostauthor to any comments by — you guessed it — the post’s author. Now, to style the author’s comments differently, all we need to do is this:

.comment { /* Reader comments */
   background: #FFFFFF;
   color: #666666;
}

.bypostauthor { /* Author comments */
   background: #880000;
   color: #FFFFFF;
}

Done! Easy, right?

Tip: If you don’t like that WordPress tells you what markup to use in the comments section, you can tell it to use your own print function:

<ul class="commentlist">
	<?php wp_list_comments('type=comment&callback=my_comment_display'); ?>
</ul>

Then, you create a function named my_comment_display(), which prints your comments as you see fit. More information on that in the Codex.

Modify Published Content

Just as we modified the feed’s content earlier, we can do the same thing with our website’s content using the the_content filter. What we’ll do here is append the author’s signature to the end of the content:

function sig_to_content($content){
   $content .= '<p><img src="'. IMAGES .'/sig.png" alt="Joseph L. Casabona" /></p>';
   return $content;
}

add_filter( "the_content", "sig_to_content" );

By now you’re getting the hang of the add_filter() and callback functions. In this case, our filter is the_content. This will add a signature to the end of both posts and pages. To filter out pages, we simply add this condition:

function sig_to_content($content){
   if(is_single()){
   		$content .= '<p><img src="'. IMAGES .'/sig.png" alt="Joseph L. Casabona" /></p>';
   		return $content;
   }
}

This function, is_single(), checks to see whether we’re viewing a single post (as opposed to the content’s relationship status).

Create A Custom Template For A Taxonomy

I started using WordPress way back in 2004, before pages, plugins or rich editing were introduced. Thinking about its evolution into an amazingly flexible platform, I remember doing custom stuff with certain categories and tags using if statements in the single.php template file. It’s much easier now.

WordPress has an incredibly sophisticated template hierarchy. Everything falls back to index.php, while templates such as page.php and single.php display various types of content differently. But you could get specific with category.php and even home.php. As you can imagine, home.php would be your home page, and category.php would display relevant posts when the visitor is viewing a category page. What you might not know is that you can get category-specific. By creating a template page named category-[slug].php or category-[id].php (that is, for example, category-news.php or category-6.php), you are telling WordPress, “Use this template specifically for this category.” I usually copy index.php or category.php and modify them.

Customize The Search Bar

On the same note, you can customize the search bar by creating a template page named searchform.php, which will include only the search form. By default (i.e. when there is no searchform.php), here’s what we’re looking at:

<form role="search" method="get" id="searchform" action="<?php echo home_url( '/' ); ?>">
    <div><label class="screen-reader-text" for="s">Search for:</label>
        <input type="text" value="" name="s" id="s" />
        <input type="submit" id="searchsubmit" value="Search" />
    </div>
</form>

The default search bar
The default search bar. (View image.)

I like to eliminate the button and label and instruct the user to hit “Enter” to search. We can do that simply by creating a searchform.php template file and adding the code. Here’s the file in its entirety:

<!--BEGIN #searchform-->
<form class="searchform" method="get" action="<?php bloginfo( 'url' ); ?>">
	<input class="search" name="s" onclick="this.value=''" type="text" value="Enter your search" tabindex="1" />
<!--END #searchform-->
</form>

Our new search bar after some CSS magic
Our new search bar after some CSS magic. (View image.)

Customize WordPress’ Log-In Screen

There are several ways to do this, mostly involving plugins. First, let’s look at a way to customize the log-in logo (and logo URL) through our own theme. Customizing the logo’s URL is easy. Just add this code to your functions.php file:

add_filter('login_headerurl', 
	create_function(false,"return 'http://casabona.org';"));

Much like with the refresh rate for our RSS widget, we are combining add_filter() and create_function() to return a different URL (in this case, my home page) when the login_headerurl hook is called. Changing the logo image is theoretically the same but does require a little extra work:

add_action("login_head", "custom_login_logo");

function custom_login_logo() {
	echo "
	<style>
	body.login #login h1 a {
		background: url('".get_bloginfo('template_url')."/images/custom-logo.png') no-repeat scroll center top transparent;
		height: 313px;
		width: 313px;
	}
	</style>
	";
}

You can see we have a hook (login_head) and a callback function (custom_login_logo()), but instead of add_filter(), we’re using add_action(). The difference between the two is that, while add_filter() replaces some text or default value, add_action() is meant to execute some code at a particular point while WordPress is loading.

In our callback function, we are overwriting the default CSS for the logo (body.login #login h1 a) with an image that we’ve uploaded to our theme’s directory. Be sure to adjust the height and width as needed. We get something like this:

That is one handsome sketch.
That is one handsome sketch. (View image.)

You could also go the plugin route and find a bunch that will help you modify the log-in page right from the WordPress admin area. I’m familiar with Custom Login, but go ahead and try a few out!

Bonus: Make A Splash Page Part Of Your Theme

While this isn’t exactly modifying WordPress’ default functionality, a lot of designers add completely separate splash pages, and WordPress makes this easy to do. Follow these steps:

  1. Create a new file in your theme directory named page-splash.php (although the name doesn’t matter).
  2. Add your HTML and CSS markup and anything else you might use. The idea here is that the markup, CSS and layout for the splash page will probably be different from the rest of the website.
  3. At the top of page-splash.php, add the following, which tells WordPress that this is a page template:
    <php /* Template Name: Splash */ ?>
  4. Add the two tags that will make your page a WordPress-ready page. Somewhere in the head (ideally, close to </head>), add <?php wp_head(); ?>. Right before the </body> tag, add <?php wp_footer(); ?>. Save it!
  5. Go into the WordPress admin panel and create a page using that template:
    default template
  6. Once you have saved the page, go to Settings → Reading, and under “Front page displays” choose the radio button “A static page.” Make the front page the splash page you created!
    splash screenshot

Conclusion

There you have it! Over 10 modifications you can make to WordPress through hooks, functions and template pages, oh my! These are ones I use frequently, but there is a whole host of hooks to do everything from adding body classes to modifying the title before it’s printed. Flexibility and not having to modify the core are what makes WordPress such a great platform! What are your favorite tips? Let us know in the comments.

Other Resources

Everything we’ve talked about in this article comes from the WordPress Codex. Here are some pages I find particularly helpful:

(al)

↑ Back to top

Joe Casabona is a web developer, teacher, and author of the book Building WordPress Themes from Scratch. He hails from Middletown, NY and has been making websites since 2002. He was introduced to WordPress in 2004 and has been working with it ever since.

  1. 1

    I’ve just learnt a couple of new WordPress tricks, so thanks for the tutorial! :-)

    6
  2. 2

    Wow lots of useful customization tips.

    I tend to search for tips like these as and when the need arises. Can you (or anyone) recommend a good place to go for a curated library of tips like these?

    1
  3. 6

    Thanks for the great post!

    I implemented “Customize WordPress’ Log-In Screen” and found that if you’re using a child theme you should replace;

    background: url(‘”.get_bloginfo(‘template_url’).”/images/custom-logo.png’) no-repeat scroll center top transparent;

    with

    background: url(‘”.get_bloginfo(‘stylesheet_directory’).”/images/custom-logo.png’) no-repeat scroll center top transparent;
    background-size: ?px ?px;

    Be sure to use background-size to override the default style.

    You can also use the following to link to your home page instead of a hard-coded url.

    add_filter(‘login_headerurl’,
    create_function(false,”return ‘/’;”));
    add_action(“login_head”, “custom_login_logo”);

    The above modifications should be attributed to Evan Mullins.

    3
    • 7

      Joseph Casabona

      June 20, 2012 9:06 am

      That’s a great point- because of the WP architecture, get_bloginfo(‘template_url’) will always grab the parent theme’s path. If you’re dealing with a child theme, get_bloginfo(‘stylesheet_directory’) will grab the proper path. My recommendation is to do something like define('TEMPPATH', get_bloginfo(‘stylesheet_directory’));, which defines a constant that you can use throughout your theme. If you need to change it, you can easily do it in one spot instead of several.

      Thanks Tim/Evan!

      0
  4. 8

    I have learnt something new, I have only just started using WordPress and this article has increased my knowledge, thank you for sharing this information.

    0
  5. 9

    Excellent tips!! Thank you so much!!

    -3
  6. 10

    Hi, Nice article, but unfortunately after days & hours of searching & doing, I couldnt device a method of creating a second contact form for a Product for example, with some extra(custom fields) to work properly using only hooks and not rambling away at the core. I wish it was as easy to customize WP with hook as most people say. The only option I was left with was to by a plugin like gravity Forms which was not what I wanted (trying/dying to learn WP the right way). I wish one of you guys/gals could put up a tut which goes through this process. None the less this is a cool post. Thnx again.

    4
  7. 11

    First off, thanks for sharing your tips. However, I do have a conflict with one area: Change The Default Source Of jQuery.

    Although this does work and is stated in the WP Codex, it should be noted that deregistering jQuery is not recommended. I realized that you are merely changing the source of jQuery (keeping the jQuery version and WP version in line), but other users may interpret this as a way to add a completely different version. Perhaps one that works with some jQuery plugin they are using.

    Although there are several reasons this is a problem, the main reason is that plugin and theme developers often rely on jQuery and have to use the version of jQuery built into WordPress. If the user is changing the version, this will often cause conflicts with these themes and plugins.

    Since you did only mention changing the source, I would like to add that this too causes a problem when updating WordPress. Now the administrator has two separate items to update in order to avoid conflicts (which we all know can be a pain).

    Other than that, there are some great tips here. Especially creating custom templates for taxonomies. I am surprised how often people fail to use custom templates for taxonomies (using conditional statements instead).

    Another great feature (not mentioned here) is the use of post formats. Post formats are a great way to alter your content based type of post you are writing.

    Cheers to a good post.

    4
  8. 15

    Jonathan Worent

    June 20, 2012 10:04 am

    I hate that I don’t hate WordPress anymore. ;)

    -3
  9. 16

    your article makes no sense to any reader that doesn’t know the context of the functions you are describing – the go into post content? a template page? where?

    -2
  10. 17

    Unfortunately I agree with ‘rickdog’. The article breezes over filters, hooks, registering menus and enquing scripts, in such a way that I would expect those that can follow it already know where to look for the code snippets and wp hacks they need.

    I also feel like this article is a bit of a random collection of WP code snippets. Don’t get me wrong, random WP code snippets are great! And Joe has covered some good ones. But from Smashing Magazine I expect there to be a little more purpose to the article. Sorry Smashing Magazine.

    5
    • 18

      I agree with rickdog and Mike. Why do so many posts neglect explaining exactly where to place code? It’s useless otherwise and reading posts that fail on this point (they’re rampant!) turns what begins as a promising chance to advance into a frustrating experience.

      My best teachers have been textbooks, but with the proliferation of blogs and self-proclaimed experts, you’d think otherwise. Maybe even that textbooks might face extinction in the near term. Countless websites are shouting at the top of their voice that they have the best of what you want only to deliver a small fraction of what they claim.

      What happened to the wisdom of under promise and over deliver? The Digital Age practices the opposite. It’s no wonder Google is demanding content. No retail business could survive, as some websites must, simply by getting people into the store.

      Enough on that.

      What needs to happen for me in this post (and others):
      (1) Identify by name the file or files into which the code is to be placed.
      (2) Describe where the file is, how to find it and how to access it (I access my WP files on the server and also thru the dashboard).
      (3) Explain how to test that it works after the code is modified.
      (4) Finally, describe any caveats that experimenters ought to know to avoid regret.

      I appreciate post publishers who take the time to publish clear, valuable content that demonstrates a desire for readers to comprehend and learn.

      0
  11. 19

    Hi Joseph

    Thanks for a great post!

    Loved the tips and tricks you shared, i think custom post types is another great addition, and there is plugins to help with the coding.

    Thanks
    Joe

    0
  12. 20

    Hey,

    Nice post, though I have couple of comments – I basically agree with rickdog a bit – for noobs (and I’m not using that word in the negative context) this tutorial won’t be helpful.

    As for the register sidebar – it’s not perfect,

    ‘before_widget’ => ”,

    should be changed to:

    ‘before_widget’ => ”,

    This is really important, since certain widgets come with a different CSS, not having it included might ultimately degenerate the markup.

    Also for the Splash Page – this approach will ONLY work if front-page.php file has not yet been defined. Page Template has lower priority than front-page.php

    Please refer to http://codex.wordpress.org/Template_Hierarchy

    Apart from the above the article outlines everything nicely :)

    0
  13. 21

    It appears that my comment was sanitized :p

    So for the register sidebar check the before_widget declaration at http://codex.wordpress.org/Function_Reference/register_sidebar (notice the % $ added)

    0
  14. 22

    keith Feldwick-Davis

    June 20, 2012 9:21 pm

    Some very handy tips here and a well written and easy to follow article.

    0
  15. 23

    Elliott Richmond

    June 20, 2012 11:19 pm

    Great resource :-)

    1
  16. 24

    Great tutorial ! But regarding jQuery I prefer this URL :
    http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js
    Because you do not have to worry about update.

    1
    • 25

      Thank you for this! :)

      1
    • 26

      You should never do that. In production, your jQuery file references should always be specific. I wrote about this a little while ago:

      http://www.impressivewebs.com/linking-to-jquery/

      As an example (mentioned in my article), $.browser is deprecated in 1.7.2 (the current release), so it may not work when that URL updates to jQuery 1.8.

      It’s bad practice to use those types of URLs that aren’t specific, so avoid them except maybe when you’re testing and experimenting locally.

      1
      • 27

        The URL links to the latest version of jQuery on Google’s servers. I don’t deny what you’re saying but I don’t think it will change anything until jQuery 2.0. However I care about good practise so thanks for the update ! :)

        0
  17. 28

    Ameya Pimpalgaonkar

    June 23, 2012 10:41 am

    This is fantastic information. I especially loved author comment highlighting and I just implemented that into my blog re-design. Thanks for all the information.

    Ameya

    0
  18. 29

    Anil Kumar Panigrahi

    June 27, 2012 11:11 pm

    Thanks for nice information Joseph. I will soon implement few changes in my blog http://www.anil2u.info which you mentioned author comment highlight from user comment.

    0
  19. 30

    Every time I visit Smashing, I find something useful.
    Thanks once again. :)

    0
  20. 31

    I’ve used ‘Highlight The Author’s Comments’ and custom ‘WordPress Login Screen’ on my website. you can see it @: tarikz.co.uk. Thanks for tips!

    0
  21. 32

    Mithilesh kumar

    July 17, 2012 2:08 am

    It’s very helpful for us

    0
  22. 33

    Thank You Joseph, It’s very helpful….

    0
  23. 34

    Thanks for the tips about the Customize WordPress’ Log-In Screen. I will try it on wptheme.fr !

    0
  24. 35

    Adored the particular guidelines an individual contributed, i do believe custom made submit sorts is an additional fantastic inclusion, then there is extensions to aid with all the code.

    http://phlebotomytraining411.com/

    0
  25. 36

    You can try out my new plugin for customizing WP Scroll Bar.
    http://codecanyon.net/item/wp-ninja-scroll-bar-customizer/4691714

    0

Leave a Comment

Yay! You've decided to leave a comment. That's fantastic! Please keep in mind that comments are moderated and rel="nofollow" is in use. So, please do not use a spammy keyword or a domain as your name, or else it will be deleted. Let's have a personal and meaningful conversation instead. Thanks for dropping by!

↑ Back to top