Useful Code Snippets For Your WordPress Theme

Get our posts emailed to you with our monthly newsletter, subscribe here.

WordPress is the most popular blogging CMS in the world and there are millions of people who use custom WordPress themes. If you are developing WordPress themes or you just want to improve your current one you will find code snippets very handy. These will help you to save time and improve your themes fast.

Most of the snippets I have collected here are short and does not require hours to implement. Just take a look at them, read a comment from the author and implement it into your blog. It is easy as that.

In this short list you will find 15 useful WordPress snippets for improving posts, navigation, images, feed and much more in your blog to make it more usable and effective.

Displaying Author info

Code displays name, gravatar and bio (taken from User settings).

<div class="author-box">

	<div class="author-pic"><?php echo get_avatar( get_the_author_email(), '80' ); ?></div>
	<div class="author-name"><?php the_author_meta( "display_name" ); ?></div>
	<div class="author-bio"><?php the_author_meta( "user_description" ); ?></div>

</div>

Show Featured Images In Feed

To encourage subscribers to visit your website, rather than letting them just consume content through your RSS feed, you might want to display only the excerpt and featured image of posts. But WordPress doesn’t display the featured image in the RSS feed by default. Use the following code to do so. You can even add HTML to it.

add_filter('the_content_feed', 'rss_post_thumbnail');
function rss_post_thumbnail($content) {
	global $post;
	if( has_post_thumbnail($post->ID) )
		$content = '<p>' . get_the_post_thumbnail($post->ID, 'thumbnail') . '</p>' . $content;
	return $content;
}

Limit excerpt words

<?php
function limit_words($string, $word_limit) {
 // creates an array of words from $string (this will be our excerpt)
  // explode divides the excerpt up by using a space character
 $words = explode(' ', $string);
 // this next bit chops the $words array and sticks it back together
  // starting at the first word '0' and ending at the $word_limit
  // the $word_limit which is passed in the function will be the number
  // of words we want to use
  // implode glues the chopped up array back together using a space character
 return implode(' ', array_slice($words, 0, $word_limit));
}
?>

This snippet let’s you limit the allowed number of words used in the excerpt. Copy this code into your functions.php and insert the content by using use this on your theme:

<?php echo limit_words(get_the_excerpt(), '41'); ?>

Pagination without plugin

<?php
function pagination($prev = '«', $next = '»') {
   global $wp_query, $wp_rewrite;
   $wp_query->query_vars['paged'] > 1 ? $current = $wp_query->query_vars['paged'] : $current = 1;
   $pagination = array(
      'base' => @add_query_arg('paged','%#%'),
      'format' => '',
      'total' => $wp_query->max_num_pages,
      'current' => $current,
      'prev_text' => __($prev),
      'next_text' => __($next),
      'type' => 'plain'
);
   if( $wp_rewrite->using_permalinks() )
      $pagination['base'] = user_trailingslashit( trailingslashit( remove_query_arg( 's', get_pagenum_link( 1 ) ) ) . 'page/%#%/', 'paged' );
   if( !empty($wp_query->query_vars['s']) )
      $pagination['add_args'] = array( 's' => get_query_var( 's' ) );
   echo paginate_links( $pagination );
};
?>

This snippet creates a classic paging navigation like the one seen in WP-PageNavi, which give a better overview for the user. It’s easy to implement and gives you total control over the output.

To implement it, just add this code to functions.php:

Now you can add the pagination using the pagination() function. Add it somewhere outside the loop, but inside the if( have_post() ) statement.

<?php if ( have_posts() ) : ?>
	<?php while ( have_posts() ) : the_post(); ?>

	// post goes here
	<?php endwhile; ?>

<div class="pagination"><?php pagination('»', '«'); ?></div>

<?php endif; ?>

WordPress also gives you some CSS classes you can use to customize the look of the new navigation. See the example and you’ll figure out how to style it:

.page-numbers { font-size: 15px; }
.page-numbers.current { color: #222; }
.page-numbers .dots { letter-spacing: 1px }
a.page-numbers  { font-size: 14px; color: #3888ff; }

Custom column for post type

<?php
add_action('manage_POSTTYPE_posts_columns', 'posts_column_hello', 10);
add_action('manage_POSTTYPE_posts_custom_column', 'posts_custom_column_hello', 10, 2);
function posts_column_hello($defaults){
   $defaults['post_hello'] = __('Hello World');
   return $defaults;
}
function posts_custom_column_hello($column_name, $post_id){
   switch($column_name) {
      case 'post_hello':
         echo 'hello world'
         break;
   }
}
?>

When creating custom post types, the standard columns(title, author, date etc.) might not be enough for your needs, and this snippet will help you to create your own.

You can add the custom columns for your custom post types by adding this to functions.php. Remember to change POSTTYPE to your post type slug.

Display your latest tweets without any plugin

Simply paste the following code anywhere in your theme files, where you want the tweets to be displayed.

Don’t forget to update the code with your username on line 3. Max items to display can be defined on line 4.

<?php
	include_once(ABSPATH . WPINC . '/feed.php');
	$rss = fetch_feed('https://api.twitter.com/1/statuses/user_timeline.rss?screen_name=catswhocode');
	$maxitems = $rss->get_item_quantity(3);
	$rss_items = $rss->get_items(0, $maxitems);  ?>
	
	<ul>
	<?php if ($maxitems == 0) echo '<li>No items.</li>';
	else
	// Loop through each feed item and display each item as a hyperlink.
	foreach ( $rss_items as $item ) : ?>
	<li>
	
	<a href='<?php echo $item->get_permalink(); ?>'>
	<?php echo $item->get_title(); ?>
	</a>
	</li>
	<?php endforeach; ?>
	</ul>

Highlight Current Page in Menu

It is always good to highlight the current page in navigation or side menu. WordPress menu functions (wp_nav_menu, wp_list_pages) automatically adds current_page_item class to li containing active link.

So it’s up to us to use the same class to highlight the current page.

/* Highlight using list element */
  li.current_page_item{
  background:#999;
  color:#fff;
}
/* Highlight using link element */
  li.current_page_item a{
  text-decoration:underline;
  background:#666;
  }

Dynamic copyright text

This snippet allows you to create a cool copyright text for your footer. This is set to automatically update the date, using the the_date() function.

Just copy the snippet in to your footer.php.

<b>(c) <?php echo date('Y'); ?></b> | <a href="<?php bloginfo('url'); ?>"><?php bloginfo('name'); ?></a> | <?php bloginfo('description'); ?>

Breadcrumbs without plugin

<?php
function the_breadcrumb() {
	echo '<ul id="crumbs">';
	if (!is_home()) {

		echo '<li><a href="';
		echo get_option('home');
		echo '">';
		echo 'Home';
		echo "</a></li>";
		if (is_category() || is_single()) {
			echo '<li>';
			the_category(' </li><li> ');
			if (is_single()) {
				echo "</li><li>";
				the_title();
				echo '</li>';
			}
		} elseif (is_page()) {
			echo '<li>';
			echo the_title();
			echo '</li>';
		}
	}
	elseif (is_tag()) {single_tag_title();}
	elseif (is_day()) {echo"<li>Archive for "; the_time('F jS, Y'); echo'</li>';}
	elseif (is_month()) {echo"<li>Archive for "; the_time('F, Y'); echo'</li>';}
	elseif (is_year()) {echo"<li>Archive for "; the_time('Y'); echo'</li>';}
	elseif (is_author()) {echo"<li>Author Archive"; echo'</li>';}
	elseif (isset($_GET['paged']) && !empty($_GET['paged'])) {echo "<li>Blog Archives"; echo'</li>';}
	elseif (is_search()) {echo"<li>Search Results"; echo'</li>';}
	echo '</ul>';
}
?>

Create a breadcrumb menu by adding this to functions.php to display the menu, just use this function to display it wherever you want:

<?php the_breadcrumb(); ?>

Highlight search-result

If you want to make it easier for your users that are using the search-function, you can highlight the word they searched on. All changes goes in search.php.

Edit the class .search-excerpt as you want your highlight to look!

<?php
  	// Replace the_exerpt() with:
 	$excerpt = get_the_excerpt();
 	$keys = explode(" ",$s);
  	$excerpt = preg_replace('/('.implode('|', $keys) .')/iu', '<strong class="search-excerpt">\0</strong>', $excerpt);
	echo $excerpt;

No excerpt available, display default message

Adding this snippet to your wordpress theme will allow you to display a default message when no excerpt has been added.

$excerpt = get_the_excerpt();
if ( empty($excerpt) ) {
    echo "no excerpt for this posting.";
}
echo $excerpt;

Display time ago(twitter style)

If you want to show how long ago something was posted (comments, post etc.), you can use WordPress human_time_diff-function. This will display something like “5 days ago“.

<?php
# For posts & pages #
echo human_time_diff(get_the_time('U'), current_time('timestamp')) . ' ago';
# For comments #
echo human_time_diff(get_comment_time('U'), current_time('timestamp')) . ' ago';

// Change to the date after a certain time
$time_difference = current_time('timestamp') - get_the_time('U');
if($time_difference < 86400) {
		//here goes the code from one of the sample above
} else {
		the_time();
};
?>

How to Display Your Latest Google+ Update on Your WordPress Blog

Simply paste the following code where you want to display your latest Google+ update. Don’t forget to put your Google+ ID on line 3.

<?php
	include_once(ABSPATH.WPINC.'/rss.php');
	$googleplus = fetch_feed("https://plusfeed.appspot.com/103329092193061943712"); // Replace 103329092193061943712 by your own ID
	echo '<a href="';
	echo $googleplus->items[0]['link']; echo '">';
	echo $googleplus->items[0]['summary'];
	echo '';
?>

Display number of Facebook fans in full text on your WordPress blog

Simply paste the following code in any of your theme files, where you want your Facebook fan count to be displayed. Don’t forget to add your page ID on line 2.

<?php
	$page_id = "YOUR PAGE-ID";
	$xml = @simplexml_load_file("https://api.facebook.com/restserver.php?method=facebook.fql.query&query=SELECT%20fan_count%20FROM%20page%20WHERE%20page_id=".$page_id."") or die ("a lot");
	$fans = $xml->page->fan_count;
	echo $fans;
?>

Customize default avatar

If you are bored by the default avatars that come with WordPress, you can easily add your own. Just create or download a better looking one, and then add the following to functions.php.

<?php
// Make a new default gravatar available on the dashboard
function newgravatar ($avatar_defaults) {
	$myavatar = get_bloginfo('template_directory') . '/images/tweaker.jpg';
	$avatar_defaults[$myavatar] = "Tweaker";
return $avatar_defaults;
}
add_filter( 'avatar_defaults', 'newgravatar' );
?>

Further Resources:

Posted by Jason Bayless