15+ Valuable Code Snippets For Your WordPress Theme

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.

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>

Source

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;
}

Source 

What to Watch Out For In WordPress 4.0?

 

Limit excerpt words

This snippet let’s you limit the allowed number of words used in the excerpt. Copy this code into your functions.php .

<?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));
}
?>

Insert the content by using use this on your theme:

Showcase of Top WordPress Gallery Plugins for Photographers
<?php echo limit_words(get_the_excerpt(), '41'); ?>

Source

 

Pagination without plugin

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.

Justblue – Premium Like Free Responsive WordPress Theme

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

<?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 );
};
?>

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.

How To Choose The Best Image SlideShow Gallery in WordPress
.page-numbers { font-size: 15px; }
.page-numbers.current { color: #222; }
.page-numbers .dots { letter-spacing: 1px }
a.page-numbers  { font-size: 14px; color: #3888ff; }

Source

 

Custom column for post type

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 tofunctions.php. Remember to change POSTTYPE to your post type slug.

<?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;
   }
}
?>

Source 

 

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>

Source 

 

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;
  }

Source 

 

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'); ?>

Source

 

Highlight keywords in search results within the_excerpt and the_title

I whipped up this little snippet that you can add to the functions.php of your wordpress theme to highlight keywords in search results for the_excerpt and the_title. A few highlight search results snippets floating around including a great one by Michael Martin. However they require you edit template files so this is my take on Michaels Idea.

function wps_highlight_results($text){
     if(is_search()){
     $sr = get_query_var('s');
     $keys = explode(" ",$sr);
     $text = preg_replace('/('.implode('|', $keys) .')/iu', '<strong class="search-excerpt">'.$sr.'</strong>', $text);
     }
     return $text;
}
add_filter('the_excerpt', 'wps_highlight_results');
add_filter('the_title', 'wps_highlight_results');

Source 

 

Breadcrumbs without plugin

Create a breadcrumb menu by adding this to functions.php to display the menu.

<?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>';
}
?>

just use this function to display it wherever you want:

<?php the_breadcrumb(); ?>

Source 

 

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;

Source 

 

Add search form to specific wp_nav_menu

Adding this snippet to the functions.php of your wordpress theme will add the search form to your wordpress wp_nav_menu. Don’t forget to update the MENU-NAME to specify the menu you wish to display within, just in case you have multiple menus.

add_filter('wp_nav_menu_items', 'add_search_form', 10, 2);
function add_search_form($items, $args) {
if( $args->theme_location == 'MENU-NAME' )
        $items .= '<li class="search"><form role="search" method="get" id="searchform" action="'.home_url( '/' ).'"><input type="text" value="search" name="s" id="s" /><input type="submit" id="searchsubmit" value="'. esc_attr__('Search') .'" /></form></li>';
        return $items;
}

 

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();
};
?>

Source

 

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("http://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 '';
?>

Source 

 

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("http://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;
?>

Source 

 

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' );
?>

Source 

 

How to automatically email contributors when their posts are published

If you’re running a multi-authored blog, it can be very cool to let your contributors know when their post are online. Today’s recipe will show you how to do this automatically each time a post is published.

Nothing complicated with this recipe. Copy the code below and paste it on your functions.php file. Then save the file, and you’re done!

function wpr_authorNotification($post_id) {
   $post = get_post($post_id);
   $author = get_userdata($post->post_author);

   $message = "
      Hi ".$author->display_name.",
      Your post, ".$post->post_title." has just been published. Well done!
   ";
   wp_mail($author->user_email, "Your article is online", $message);
}
add_action('publish_post', 'wpr_authorNotification');

Source