Useful WordPress Code Snippets and Hacks

    written by Nikola Lazarevic

    When coding WordPress themes, especially if you do it regularly, its really useful to have a selection of code snippets in your toolbox to just ‘copy-n-paste’ as and when the functionality needs. Here are useful code snippets and hacks that will help you extend the capabilities of your WordPress site, and of course save your time.

    How to Display a Thumbnail from a Youtube Using a Shortcode

    First, you need to create the shortcode. To do so, copy the code below and paste it into your functions.php file.

    /*
        Shortcode to display youtube thumbnail on your wordpress blog.
        Usage:
        [youtube_thumb id="VIDEO_ID" img="0" align="left"]
        VIDEO_ID= Youtube video id
        img=0,1,2 or 3
        align= left,right,center
    */
    function wp_youtube_video_thumbnail($atts) {
         extract(shortcode_atts(array(
              'id' => '',
              'img' => '0',
              'align'=>'left'
         ), $atts));
        $align_class='align'.$align;
        return '<img src="<a href="http://img.youtube.com/vi/'.$id.'/'.$img.'.jpg&quot" rel="nofollow">http://img.youtube.com/vi/'.$id.'/'.$img.'.jpg&quot</a>; alt="" class="'.$align_class.'" />';
    }
    add_shortcode('youtube_thumb', 'wp_youtube_video_thumbnail');
    

    Once done, you can use the shortcode. It accept 3 parameters: The video ID, the image size (0 for 480*360px, 1 for 120*90) and the image alignment.

    [youtube_thumb id="rNWeBVBqo2c" img="0" align="center"]
    

    Source

    Turn On More Buttons in the WordPress Visual Editor

    The Visual Editor in WordPress Admin is missing out some basic buttons like hr, del and ins. To activate more buttons, just add the following to functions.php:

    function add_more_buttons($buttons) {
     $buttons[] = 'hr';
     $buttons[] = 'del';
     $buttons[] = 'sub';
     $buttons[] = 'sup';
     $buttons[] = 'fontselect';
     $buttons[] = 'fontsizeselect';
     $buttons[] = 'cleanup';
     $buttons[] = 'styleselect';
     return $buttons;
    }
    add_filter("mce_buttons_3", "add_more_buttons")
    

    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 the Number of Comments by Author

    Copy the function below into your functions.php:

    function author_comment_count(){
     
    	$oneText = '1';
    	$moreText = '%';
     
    	global $wpdb;
     
    	$result = $wpdb->get_var('
    		SELECT
    			COUNT(comment_ID)
    		FROM
    			'.$wpdb->comments.'
    		WHERE
    			comment_author_email = "'.get_comment_author_email().'"'
    	);
     
    	if($result == 1): 
     
    		echo str_replace('%', $result, $oneText);
     
    	elseif($result > 1): 
     
    		echo str_replace('%', $result, $moreText);
     
    	endif;
     
    }
    

    To display an author’s total number of comments, use the function like this inside of your comments loop:

    author_comment_count();
    

    Source

    How to Display Most Popular Posts from a Specific Category

    Put the code below, in your theme sidebar or wherever You want to display your popular posts from specific category.

    
    <?php
    $args=array(
      'cat' => 3,
      'orderby' => 'comment_count',
      'order' => 'DESC',
      'post_type' => 'post',
      'post_status' => 'publish',
      'posts_per_page' => 6,
      'caller_get_posts'=> 1
    );
    $my_query = null;
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) { ?>
    	<ul>
    	<?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
    	<li><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
    	<?php  endwhile; ?>
    	</ul>
    <?php }
    
    wp_reset_query(); ?>
    

    Remeber to replace ’3′ with the category ID you want to display.

    Source

    Exclude Category from Feeds

    Great for excluding categories or customizing feeds in all sorts of fun ways. Add this to your functions.php file.

    // custom feed query
    function customFeedquery($query) {
    	if(is_feed()) {
    		$query->set('cat','-8'); // exclude category 8
    		return $query;
    	}
    }
    add_filter('pre_get_posts', 'customFeedquery');
    

    Source

    How to Remove the “Read More” Jump

    Paste the following snippet into your functions.php file:

    function wdc_no_more_jumping($post) {
         return '<a href="'.get_permalink($post->ID).'" class="read-more">'.'Continue Reading'.'</a>';
    }
    add_filter('excerpt_more', 'wdc_no_more_jumping');
    

    Source

    Share Via Email Link

    A simple link that opens users default email client to send an email to a friend or colleague.

    <?php echo "<a href="mailto:type%20email%20address%20here?subject=I%20wanted%20to
    %20share%20this%20post%20with%20you%20from%20
    <?php bloginfo('name'); ?>&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;body=<?php the_title(); ?> - <?php the_permalink(); ?>"
    title="Email to a friend/colleague"target="_blank">Share via Email</a>"; ?>
    

    Source

    Insert Author Bio for Each Post

    Start giving your authors proper credit by inserting the following code into your functions.php file. An author bio will be automatically be displayed at the end of every post.

    function get_author_bio ($content=''){
        global $post;
    
        $post_author_name=get_the_author_meta("display_name");
        $post_author_description=get_the_author_meta("description");
        $html="<div class='clearfix' id='about_author'>\n";
        $html.="<img width='80' height='80' class='avatar' src='http://www.gravatar.com/avatar.php?gravatar_id=".md5(get_the_author_email()). "&default=".urlencode($GLOBALS['defaultgravatar'])."&size=80&r=PG' alt='PG'/>\n";
        $html.="<div class='author_text'>\n";
        $html.="<h4>Author: ".$post_author_name."</h4>\n";
        $html.= $post_author_description."\n";
        $html.="</div>\n";
        $html.="<div class='clear'></div>\n";
        $content .= $html;
        }
    
        return $content;
    }
    
    add_filter('the_content', 'get_author_bio');
    

    Source

    Disable Self Trackbacks

    WordPress trackback system makes sure that other blogs are noticed when you link to them. Problem is, when you link to one of your own posts, on your own website, a trackback will be displayed although the link is coming from you.
    To disable this, put this in functions.php:

    function disable_self_ping( &$links ) {
        foreach ( $links as $l => $link )
            if ( 0 === strpos( $link, get_option( 'home' ) ) )
                unset($links[$l]);
    }
    add_action( 'pre_ping', 'disable_self_ping' );
    

    Source

    Customize Default Avatar

    If you are bored by the default avatars that comes with WordPress, you can easily add your own. Just create or download a better looking one, and then add the following to functions.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

    Automatic Social Media Links

    This would go inside the loop, probably underneath the_content(), probably in your single.php file.

    // bookmark on Delicious
    <a rel="nofollow" href="http://delicious.com/post?url=<?php the_permalink(); ?>&amp;title=<?php echo urlencode(get_the_title($id)); ?>" title="Bookmark this post at Delicious">Bookmark at Delicious</a>
    
    // submit to Digg
    <a rel="nofollow" href="http://digg.com/submit?phase=2&amp;url=<?php the_permalink(); ?>" title="Submit this post to Digg">Digg this!</a>
    
    // tweet on Twitter
    <a rel="nofollow" href="http://twitter.com/home?status=<?php echo urlencode("Currently reading: "); ?><?php the_permalink(); ?>" title="Share this article with your Twitter followers">Tweet this!</a>
    
    // submit to StumbleUpon
    <a rel="nofollow" href="http://www.stumbleupon.com/submit?url=<?php the_permalink(); ?>&amp;title=<?php echo urlencode(get_the_title($id)); ?>" title="Share this post at StumbleUpon">Stumble this!</a>
    
    // share on Facebook
    <a rel="nofollow" href="http://www.facebook.com/sharer.php?u=<?php the_permalink();?>&amp;t=<?php echo urlencode(get_the_title($id)); ?>" title="Share this post on Facebook">Share on Facebook</a>
    
    // submit to Blinklist
    <a rel="nofollow" href="http://blinklist.com/index.php?Action=Blink/addblink.php&amp;url=<?php the_permalink(); ?>&amp;Title=<?php echo urlencode(get_the_title($id)); ?>" title="Share this post on Blinklist" >Blink This!</a>
    
    // store on Furl
    <a rel="nofollow" href="http://furl.net/storeIt.jsp?t=<?php echo urlencode(get_the_title($id)); ?>&amp;u=<?php the_permalink(); ?>" title="Share this post on Furl">Furl This!</a>
    
    // submit to Reddit
    <a rel="nofollow" href="http://reddit.com/submit?url=<?php the_permalink(); ?>&amp;title=<?php echo urlencode(get_the_title($id)); ?>" title="Share this post on Reddit">Share on Reddit</a>
    

    Source

    How to Easily Disable Theme Changing

    Simply paste the following piece of code in your functions.php file:

    add_action('admin_init', 'slt_lock_theme');
    function slt_lock_theme() {
    	global $submenu, $userdata;
    	get_currentuserinfo();
    	if ($userdata->ID != 1) {
    		unset($submenu['themes.php'][5]);
    		unset($submenu['themes.php'][15]);
    	}
    }
    

    Source

    Pagination Without Plugin

    To implement it, just add this code to functions.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; ?>
    

    Source

    Limit Search Results to Specific Post Types

    Just place this in your functions.php file, and it will automatically filter your Search Results.

    function SearchFilter($query) {
        if ($query->is_search) {
            $query->set('post_type',array('post','page'));
        }
    return $query;
    }
    add_filter('pre_get_posts','SearchFilter');
    

    Source

    Include jQuery in WordPress Theme

    The following is the best way to go about it. Add the following to the theme’s functions.php file:

    if( !is_admin()){
       wp_deregister_script('jquery');
       wp_register_script('jquery', ("http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"), false, '1.3.2');
       wp_enqueue_script('jquery');
    }
    

    Source

    Track Post Views Without a Plugin Using Post Meta

    Add this snippet into the functions.php of your wordpress theme then follow step 1. and step 2. to display the number of views for each post.

    function getPostViews($postID){
        $count_key = 'post_views_count';
        $count = get_post_meta($postID, $count_key, true);
        if($count==''){
            delete_post_meta($postID, $count_key);
            add_post_meta($postID, $count_key, '0');
            return "0 View";
        }
        return $count.' Views';
    }
    function setPostViews($postID) {
        $count_key = 'post_views_count';
        $count = get_post_meta($postID, $count_key, true);
        if($count==''){
            $count = 0;
            delete_post_meta($postID, $count_key);
            add_post_meta($postID, $count_key, '0');
        }else{
            $count++;
            update_post_meta($postID, $count_key, $count);
        }
    }
    

    STEP 1
    Place this snippet bellow “setPostViews” within the single.php inside the loop.

    <?php
    setPostViews(get_the_ID());
    ?>
    

    STEP 2
    Place this snippet bellow within the template where you would like to display the number of views.

    <?php
    echo getPostViews(get_the_ID());
    ?>
    

    Source

    DISPLAY POST VIEWS WITHIN ADMIN POST COLUMNS
    You can add a “Views” column to the posts columns by adding this in functions.php:

    add_filter('manage_posts_columns', 'posts_column_views');
    add_action('manage_posts_custom_column', 'posts_custom_column_views',5,2);
    function posts_column_views($defaults){
        $defaults['post_views'] = __('Views');
        return $defaults;
    }
    function posts_custom_column_views($column_name, $id){
    	if($column_name === 'post_views'){
            echo getPostViews(get_the_ID());
        }
    }
    

    Source

    Get Facebook Fan Count Using Get_Transient and Wp_Remote_Get

    Adding this snippet to the functions.php of your wordpress theme will let you cache and display your Facebook fan count.

    function get_fan_count(){
             $fb_id = '106900272716297';
             $count = get_transient('fan_count');
        if ($count !== false) return $count;
             $count = 0;
             $data = wp_remote_get('http://api.facebook.com/restserver.php?method=facebook.fql.query&query=SELECT%20fan_count%20FROM%20page%20WHERE%20page_id='.$fb_id.'');
       if (is_wp_error($data)) {
             return 'whoa error!!!';
       }else{
             $count = strip_tags($data[body]);
       }
    set_transient('fan_count', $count, 60*60*24); // 24 hour cache
    return $count;
    }
    

    Add the this into your WordPress theme in the location you wish to display the count.

    <? echo get_fan_count(); ?>
    

    Source

    Get Feedburner Count Using Get_Transient and Wp_Remote_Get

    Adding this snippet to the functions.php of your WordPress theme will get your feedburner subscriber count.

    function feed_subscribers(){
            $feed_url = 'http://feeds.feedburner.com/yourname';
            $count = get_transient('feed_count');
            if ($count != false) return $count;
    	$count = 0;
            $data  = wp_remote_get('http://feedburner.google.com/api/awareness/1.0/GetFeedData?uri='.$feed_url.'');
       if (is_wp_error($data)) {
            return 'error';
       }else{
    	$body = wp_remote_retrieve_body($data);
    	$xml = new SimpleXMLElement($body);
    	$status = $xml->attributes();
    	if ($status == 'ok') {
    		$count = $xml->feed->entry->attributes()->circulation;
    	} else {
    		$count = 300; // fallback number
    	}
       }
    	set_transient('feed_count', $count, 60*60*24); // 24 hour cache
    	echo $count;
    }
    

    Then add this to your WordPress theme in the location you wish to display the RSS feed subscriber count.

    <? feed_subscribers(); ?>
    

    Source

    Cached Twitter Follower Count

    function get_follower_Count(){
        $count = get_transient('follower_count');
    if ($count !== false) return $count;
        $count = 0;
        $data = wp_remote_get('http://api.twitter.com/1/users/show.json?screen_name=YOURNAME');
    if (!is_wp_error($data)) {
        $value = json_decode($data['body'],true);
        $count = $value['followers_count'];
    }
    set_transient('follower_count', $count, 60*60); // 1 hour cache
    return $count;
    }
    

    Add the first section of code to the functions.php of your wordpress theme. This code will cache your Twitter follower number for 1 hour and display the count within your template.

    <?
    get_follower_count();
    ?>
    

    Source

    Reduce Spam on Your WordPress Blog by Using .htaccess

    Simply paste the following lines into your .htaccess file. This file is located at the root of your WordPress install. Remember to always make a backup of your .htaccess file before editing it so, you’ll be able to restore it if something went wrong.

    <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_METHOD} POST
    RewriteCond %{REQUEST_URI} .wp-comments-post\.php*
    RewriteCond %{HTTP_REFERER} !.*yourdomainname.* [OR]
    RewriteCond %{HTTP_USER_AGENT} ^$
    RewriteRule (.*) ^http://%{REMOTE_ADDR}/$ [R=301,L]
    </IfModule>
    

    Don’t forget to replace yourdomainname on line 5 by your real domain name.

    Source

    Auto-Updating Date

    Copyright &copy; 2008-<?php echo date('Y'); ?>
    

    Reset Admin Password Through Database

    You’ll need to be able to run SQL on that database, like for example, through phpMyAdmin.

    UPDATE `wp_users` SET `user_pass` = MD5( 'new_password_here' ) WHERE `wp_users`.`user_login` = "admin_username";
    

    Source

    Make an excellent website from this free wordpress theme and improve your error page with wordpress tools.

     
    Authored by

    Web Designer, Blogger, M.Sc in Electronic Engineering from Nis, Serbia. Founder of webexpedition18.com. You can find me on Twitter.

    Enjoyed this story?

    Please leave your comment about this post on the comment section below. If you liked it tell your friends by tweeting it. You can also subscribe to our feed by rss or email.

7 Comments
ADD COMMENT
  • Web Design Company Mumbai says:

    October 3, 2011

    Thanks for the useful code snippet.

  • David says:

    October 5, 2011

    Great collection of WP snippets, disabling ‘self track backs’ caught my eye – pretty handy for future dev work.

  • James George says:

    October 6, 2011

    Wow! That’s all I have to say. You posted some really cool and unique information that I haven’t seen plastered all over other sites. Great job! Consider your site on my list!

  • Dzinepress says:

    October 6, 2011

    i love to use some of your snippets even add in my library.

  • Web Design Company Mumbai says:

    October 10, 2011

    Thanks for sharing the snnipets.

  • Web Design Company Mumbai says:

    October 18, 2011

    Thanks for sharing the Code.

  • stay says:

    October 21, 2011

    A very useful article. Give me more tricks for WordPress.