9 Useful Snippets for Your WordPress Functions

Seeing as how the WordPress category is one of the most successful and popular categories on Themeforest, it seems fit to cover some useful tips on the topic. When it comes to WordPress, many designers seem to be scared off or uninterested in the functions.php file, when really it can be one of the most useful files for your WordPress theme. Today, we will review nine superb code snippets you can use to enhance your theme.

One of the biggest benefits of the functions.php file, is that it allows us some abstraction from our regular theme files. Instead of hard coding information or queries into, say, our single.php file, we can use our functions.php file instead to alter it. Later on down the road, if we need to make any changes, we can simply edit one file instead of many.

1. Make Your Theme Widget Ready

A widget ready sidebar could almost be consider essential for any Wordpress theme. Widgets allow the end user to easily and quickly customize specific content on their WordPress theme. Luckily for us, making our sidebar widget ready is very simple. First, add the below code to your functions.php file:

if ( function_exists('register_sidebar') )
    register_sidebar(array(
        'before_widget' => '<li class="widget">',
        'after_widget' => '</li>',
        'before_title' => '<h2 class="widgettitle">',
        'after_title' => '</h3>',
    ));

The code above registers our sidebar widgets and formats them with some basic HTML markup, this allows the designer to easily use those elements to style the widgets and page as they see fit. Now, all we need to do is add a conditional php statement in our sidebar, like so:

<?php 
		if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar() ) : 
		?>
		<!--non widget and sidebar information go here-->
 
		<?php endif; ?>

Our theme is now widget ready, if there are no widgets enabled, the default sidebar information will be displayed. If the widgets are enabled by the user, then the widgets will be displayed along with any markup that we declared in our functions.php file.

2. Add Multiple Sidebar Widgets

What if we wanted to have multiple sidebars or sections for other widgets to be added? This is very similar to the code above, however, we need to let WordPress know we are going to register multiple sidebars. We can achieve this easily by doing something like the below snippet:

<?php
			if ( function_exists('register_sidebar') )
			register_sidebar(array('name'=>'-ColumnOne',
			'before_widget' => '<li class="widget">',
			'after_widget' => '</li>',
			'before_title' => '<h2 class="widgettitle">',
			'after_title' => '</h3>',
		));
		register_sidebar(array('name'=>'-ColumnTwo',
			'before_widget' => '<li class="widget">',
			'after_widget' => '</li>',
			'before_title' => '<h2 class="widgettitle">',
			'after_title' => '</h3>',
		));
	?>

The only other thing we would need to do is add our additional conditional statement like we did in Step 1:

<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('-ColumnOne') ) : ?>
			<!--Default sidebar info here-->
			<!--do the same thing for -ColumnTwo -->
		<?php endif; ?>
Widgets Screenshot

Additional Resources:

3. Promote Your RSS Feed After Individual Articles

You may have noticed that many blogs have a little bit of self promotion that occurs at the end of their articles. Such promotion usually contains things like encouraging you to subscribe to RSS feeds or maybe a list of related posts. Using our functions.php file, we can automatically append a little bit of self promotion onto the end of our individual articles.

<?php
		function promote_blog($content){
			echo $content;
			if(is_single()){
		?>
		<div class='promote'>
			<h3>Enjoy this article?</h3>
			<p>Consider <a href="<?php bloginfo('rss2_url'); ?>" title="Subscribe via RSS">subscribing to our RSS feed!</a></p>
		</div>
		<?php
			}
		}
		add_filter('the_content', 'promote_blog');
		?>

You could easily add any additional classes or divs you need and style away. Below is a great example of promoting ones website after the individual article using WordPress by WP Engineer:

Promotion_Screenshot

4. Enable Adsense Shortcode

This tip comes from the WordPress expert, Jean-Baptiste Jung, from his article on Smashing Magazine. Basically, wordpress allows developers and theme creators to write functions that allow the user to use shortcode, i.e., [adsense]. This kind of ‘pseudo’ code makes it easy for end users to insert elements where they would like without knowing about coding.

Knowing that we can create shortcodes, we can create one to insert a Google Adsense ad anywhere in theme theme.

function showads() {  
     	return '<div id="adsense"><script type="text/javascript"><!--  
     	google_ad_client = "pub-XXXXXXXXXXXXXX";  
    	 google_ad_slot = "4668915978";  
    	 google_ad_width = 468;  
    	 google_ad_height = 60;  
    	 //-->  
		 </script>  
 
		 <script type="text/javascript"  src="http://pagead2.googlesyndication.com/pagead/show_ads.js">  
 		 </script></div>';  
 }  
 
 add_shortcode('adsense', 'showads');

Now whenever you would like to add your adsense code in your articles or pages, just simply insert [adsense].

Article Source

5. Add a ‘Send to Twitter’ Link With TinyURLs in the Status

If you’re on Twitter and want to give users the option of sending the current article to their status with your link (in the form of a TinyURL) and post title, you can add this custom function to your functions.php file. As noted, credit to my friend Brian Cray for the one line TinyURL solution:

if(!function_exists('dd_tiny_tweet_init')){
 
	function dd_tiny_tweet_init($content){
		//Thanks to http://briancray.com for the one line $tiny_tweet_url solution. 
		$tiny_tweet_url = file_get_contents('http://tinyurl.com/api-create.php?url=' . urlencode('http://' . $_SERVER['HTTP_HOST']  . '/' . $_SERVER['REQUEST_URI']));
		//Grab the title of the current post
		$tiny_tweet_title = get_the_title();
		//Reduce title to 100 characters
		$tiny_tweet_title = substr($tiny_tweet_title, 0,100);
		//Append an ellipsis to the end
		$tiny_tweet_title .='...';
		//Set up the status and url to send to twitter
		$tiny_tweet_status_url = 'http://twitter.com/home?status=Currently reading "'.$tiny_tweet_title."\" ".$tiny_tweet_url;
		//If the current page is an individual article, promote it with a Twitter link!
		if(is_single()){
			$content .=  '<div class=\'tiny_tweet\'>Enjoy this post? <a href=\''.$tiny_tweet_status_url.'\'>The give it a tweet!</a></div>';
		}
	return $content;
  }
  add_filter('the_content', 'dd_tiny_tweet_init');
 
}

Note you will need to make sure your host supports file_get_contents() for this to work. Below is a screenshot of the basic output:

SendToTwitterScreenshot

The comments in the code above should explain most of it. When a user views an individual article, they can click on the link to send the article to their current Twitter status. If our article was named ‘Hello World’, then the status would read:

Currently reading ‘Hello World…’ http://tinyurl.com/5ng3n8

Customize and style to your liking and you have a fully functioning send to Twitter link!

6. Disable Commenting on Posts Older Than 1 Month

Sometimes blog conversations can get a little off topic and out of hand to say the least. If you wish to keep things relative and up to date on the latest discussions, you cal close comments automatically after one month. This handy tip comes to us from forthelose and looks like so:

<?php
 
		function close_comments( $posts ) {
 
			if ( !is_single() ) { return $posts; }
 
			if ( time() - strtotime( $posts[0]->post_date_gmt ) > ( 30 * 24 * 60 * 60 ) ) {
			$posts[0]->comment_status = 'closed';
			$posts[0]->ping_status    = 'closed';
			}
 
		return $posts;
		}
		add_filter( 'the_posts', 'close_comments' );
 
		?>

You can find a nice example of this on the website of Elliot Jay Stocks:

ClosedComments

7. Add a PayPal Donation Link

Perhaps you run a website or blog that likes to give away free tutorials, images, and/or code and you would like to offer your readers a way to give back. Using a custom PayPal url and function, we can automatically create a shortcut code to create a donation link. All credit to Blue Anvil for this wonderful snippet:

function donate_shortcode( $atts ) {
   			 extract(shortcode_atts(array(
       			 'text' => 'Make a donation',
       			 'account' => 'REPLACE ME',
       			 'for' => '',
  			  ), $atts));
 
   			 global $post;
 
    		if (!$for) $for = str_replace(" ","+",$post->post_title);
 
   			return '<a class="donateLink" href="https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&business='.$account.'&item_name=Donation+for+'.$for.'">'.$text.'</a>';
 
}
add_shortcode('donate', 'donate_shortcode');

Next, just replace the ‘text’ and ‘account’ values with your own within this function. Now all you need to do is add the shortcode wherever you like in your post, i.e. [donate]

PayPalDonateScreenshot

8. Change the Default Gravatar

Our next tip comes to us from CatsWhoCode and is a simple option to change the default WordPress gravatar with one of your own. This is a fantastic way to further brand yourself and your website.

if ( !function_exists('fb_addgravatar') ) {
 
	function fb_addgravatar( $avatar_defaults ) {
 
		$myavatar = get_bloginfo('template_directory').'/gravatar.gif';
        //default avatar below
		$avatar_defaults[$myavatar] = 'Exciting new gravtar';
 
		return $avatar_defaults;
	}
 
	add_filter( 'avatar_defaults', 'fb_addgravatar' );
}

In the above code, change ‘Exciting new gravatar’ and point it to the filename of your new Gravatar and you’re done!

9. Changing Your WordPress Feed Links Without .htaccess

For our last function we will have a look at a snippet written by WordPress Guru, Justin Tadlock. Though there are many plugins that can do this for us, it is quite easy to pull off. For the snippet we will assume you would like the links to point to a feedburner account.

function custom_feed_link($output, $feed) {
 
	$feed_url = 'http://feeds.feedburner.com/justintadlock';
 
	$feed_array = array('rss' => $feed_url, 'rss2' => $feed_url, 'atom' => $feed_url, 'rdf' => $feed_url, 'comments_rss2' => '');
	$feed_array[$feed] = $feed_url;
	$output = $feed_array[$feed];
 
	return $output;
	}
 
	function other_feed_links($link) {
 
	$link = 'http://feeds.feedburner.com/justintadlock';
	return $link;
 
	}
	//Add our functions to the specific filters
	add_filter('feed_link','custom_feed_link', 1, 2);
	add_filter('category_feed_link', 'other_feed_links');
	add_filter('author_feed_link', 'other_feed_links');
	add_filter('tag_feed_link','other_feed_links');
	add_filter('search_feed_link','other_feed_links');

Change the $feed_url variable to your current feed and go grab some lunch!

FeedBurnerScreenshot

Have any custom functions or code snippets you like to use? Share them with us in the comments section below, and don’t forget to check out our WordPress for Designers series we are currently running. Happy coding!



32

Comments