Feedback Form
Customer? Login here
 

Five Awesome functions.php Tricks in WordPress

1. Change the default gravatar

Something that ‘bigger’ blogs often do is have a customized avatar for users who don’t have an avatar themselves. How do they do it? Through the functions.php file of course!

avatars

First thing to do is to create your exciting new avatar, 100 by 100 pixels. Next, upload your avatar to /wp-content/themes/yourtheme/images/, having saved it as gravatar.jpg.

Now that you’ve created your avatar, open up your functions.php file and add the code below.

 <php if ( !function_exists('fb_addgravatar') ) {
    function fb_addgravatar( $avatar_defaults ) {
    $myavatar = get_bloginfo('template_directory').'/images/gravatar.jpg';
    //default avatar
    $avatar_defaults[$myavatar] = 'Exciting new gravtar';
    return $avatar_defaults;
    }
 add_filter( 'avatar_defaults', 'fb_addgravatar' );
}
?>

displayavatar

Next, to activate your shiny new avatar, in the WordPress backend, under ‘Settings’, click ‘Discussion’. Then scroll down to avatars, select your exciting new avatar and click ‘Save Changes’. Done.

2. Create an awesome options page

No doubt you’ve seen theme options pages in WordPress themes. The more inquisitive of you might have even wondered how they’re made. The answer is of course, in the functions.php page!

hybridoptions

Creating an options page isn’t as hard as you might think, and it’s something that I’ve covered on my blog – if you want to create an options page, it’s best you take a look there. Here though, we’ll take a brief look at the very basics of options pages.

First thing to do is to open up your functions.php file and add the following code:


<?php
// Theme options page
// Created using the tut at Nometech.com - http://www.nometech.com/blog/create-an-awesome-wordpress-theme-options-page-part-1
$themename = "hexadecimal";
$shortname = "hd";
$options = array (

Let’s take a look at the code. $themename is the name of your theme, funnily enough. You’ll need to change that. You’ll also need to change the $shortname to a shortened name of your theme’s name. For example, in the code above, the theme is called ‘hexadecimal’. This is shortened to ‘hd’. Simple.

As we are editing the functions.php file, obviously the code we’re writing is php. What this means is that we don’t need to style each section of our options page individually; using php’s arrays, you can specify that you want an element to have certain properties, which the php will apply later. For example, the code below lets the user enter some text, perhaps changing the footer copyright or the like.

(to keep this tut from being stupidly long, I’ve missed out a couple of important bits of code you’ll need to make this work, but you can download the code here).

 array(
"name" => "Some text you can customise",
"type" => "title"),

array(
"type" => "open"),

array(
"name" => "What is your name?",
"desc" => "Names are an integral part of our society. My name is Frederick. What's yours?",
"id" => $shortname."_my_name",
"type" => "text",
"std" => "Frederick"),

array(
"type" => "close"),

array(
"type" => "submit"),

In the code above, first we’re telling the code to insert the code filed under open (more on that below), then give it a title and description. The $shortname is what you can use to implement the options page into your theme. Below that, we’re telling the code to insert the code filed under text, with a default (ie what is displayed when you haven’t changed anything) of ‘Frederick’. We’re then closing and submitting.

We’ve specified a number of elements – ‘close, submit’ etc. I’ll quickly run through how this would get styled – in the code below, we’ll style the text box we use above:

 <?php break;
case 'text':
?>

<div style="width:800px; padding:0px 0px 10px; margin:0px 0px 10px; border-bottom:1px solid #ddd; overflow:hidden;">

<span style="font-family:Arial, sans-serif; font-size:16px; font-weight:bold; color:#444; display:block; padding:5px 0px;">
<?php echo $value['name']; ?>
</span>

<input style="width:200px;" name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>" type="<?php echo $value['type']; ?>" value="<?php if ( get_settings( $value['id'] ) != "") { echo stripslashes(get_settings( $value['id'] )); } else { echo stripslashes($value['std']); } ?>" />

<br/>

<span style="font-family:Arial, sans-serif; font-size:11px; font-weight:bold; color:#444; display:block; padding:5px 0px;">

<?php echo $value['desc']; ?>

</span>
</div>

So that’s a crash course in options page making, but it is only the very basics – I’ve written a more in depth tutorial about it, including how to implement your options in parts one and two.

3. Add widgets to your theme

Widgets are just one of the things that you simply must have when building/releasing a theme these days. Adding widgets to your sidebar is really easy – add the code below to your functions.php.

<?php if ( function_exists('register_sidebar') )
register_sidebar(array(
'name' => 'Sidebar',
'before_widget' => '<div class="widget">',
'after_widget' => '</div>',
'before_title' => '<h3 class="widget">',
'after_title' => '</h3>',
)); ?>

Lets analyse the code – before the widget the CSS class ‘widget’ will open, and before the title the h3 class widget will open. Using these two, you can style your widgets, but not before you’ve implemented the widgets into your sidebar, with the following code:

<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('Sidebar') ) : ?><?php endif; ?>

It’s all very well having a single widgetized area, but why not have more? Just copy and paste the code above into your functions.php file, changing the name from ‘Sidebar’ to something that suits where you’re putting the widget, perhaps ‘Footer’.

This final way to add widgets to your theme was inspired by a post on Smashing Magazine on the subject of widgets. What is this final way to add widgets? In between posts. Again, add the code above to the functions.php file, changing the name to something more appropriate, perhaps ‘In-Between-Posts’. Once you’ve done that, open up your index.php file or home.php file and before the , add the code below:

<?php if ($count==2) { ?>
<?php dynamic_sidebar('In-Between-Posts1') ?>
<?php } ?>
<?php $count = $count + 1; ?>
<?php endwhile; ?>

4. Create shortened URLs for Twitter

Automatically shortening your blog posts’ URLs for Twitter is really easy to do with the functions.php file. I’ll show you how to shorten your posts’ URLs with tr.im and tinyurl (code from WPRecipes.com). Lets start with tr.im. Add the code below to your functions.php file:

function getTrimUrl($url) { $tinyurl = file_get_contents("http://api.tr.im/api/trim_simple?url=".$url); return $tinyurl; }

And then to use the shortened URLs with the code below, within the loop in your single.php file.

<?php $turl = getTrimUrl(get_permalink($post->ID)); echo 'Short Url for this post: <a href="'.$turl.'">'.$turl.'</a>' ?>

Whilst tr.im is arguably a better shortening service, tinyurl is also very popular. Thankfully, it is also very easy to integrate tinyurl’d URLs into your blog posts with the code below in your functions.php file:

function getTinyUrl($url) { $tinyurl = file_get_contents("http://tinyurl.com/api-create.php?url=".$url); return $tinyurl; }

And then in your single.php file, within the loop:

<?php $turl = getTinyUrl(get_permalink($post->ID)); echo 'Tiny Url for this post: <a href="'.$turl.'">'.$turl.'</a>' ?>

5. Display images on archive pages (and the homepage) without using custom fields

A lot of WordPress themes use custom fields to display images, which most users understandably find a pain to do. However, it needn’t be that hard to do! As was posted in the WordPress support forums a while back, with the functions.php file, you can easily get around the need for custom fields:

 function catch_that_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches [1] [0];

// no image found display default image instead
if(empty($first_img)){ $first_img = "/images/default.jpg"; } return $first_img; }

Once you’ve inserted the code to your functions.php file, all that is left to do is to replace your custom field-getting code in the index.php/home.php file and replace it with the code below.

<img src="<?php echo catch_that_image() ?>" alt=""/>

Tags: , ,

Posted by: Alex Denning

Written by Alex Denning, a blogger and WordPress freelancer from London. He can be found on Twitter as well as on his personnal blog WPShout.com

Similar Posts
Posted on August 11th, 2009

7 Responses to “ Five Awesome functions.php Tricks in WordPress ”

WpthemesMall

Nice Collection Thanks

Blog Header Guy

Thanks for these tips. I’ve been wondering how these premium themes added all those options.

Now I have no excuses to make my own.

Thanks.

Edward

Someone copied your article here:

teratips.com/change-default-gravatar-functions-php/

strkgroups

Ohh these are what i am looking for

Ashfame

Hi,

I tried changing my gravatar but faced a weird issue.
The avatar appeared under my dashboard and I can see it everywhere in the dashboard but its not showing up on posts.

Any ideas?

Also there is a small typo of <?php in the code

Ashfame

Never mind! I deleted that code and got it working by changing the argument of a function in the theme file.

Trackbacks

  1. How to Change the default gravatar - functions.php | Blogging Tips by TeraTips.com

Leave a Reply