20 Code Snippets for Extending the Functionality of WordPress


By

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. Not just your most commonly used code, but also some snippets that can, when required, extend WordPress even further.

Today, we have code snippets that focus on extending the functionality of WordPress even further. Just like the previous post, there are 20 very useful snippets in total, covering many areas of theme development, including tracking page-views, custom shortcodes and widgets, custom title lengths and excerpts, and much, much more.

You might also like these useful .htaccess snippets & hacks, these WordPress SQL Query Snippets, or these snippets that make WordPress user-friendly for your clients.

Automatically Add Twitter & Facebook Buttons to WordPress Posts

This snippet will add Twitter and Facebook buttons to the bottom of all your posts. All you have to do is paste the code below into your functions.php file:

function share_this($content){
    if(!is_feed() && !is_home()) {
        $content .= '<div class="share-this">
                    <a href="http://twitter.com/share"
class="twitter-share-button"
data-count="horizontal">Tweet</a>
                    <script type="text/javascript"
src="http://platform.twitter.com/widgets.js"></script>
                    <div class="facebook-share-button">
                        <iframe
src="http://www.facebook.com/plugins/like.php?href='.
urlencode(get_permalink($post->ID))
.'&amp;layout=button_count&amp;show_faces=false&amp;width=200&amp;action=like&amp;colorscheme=light&amp;height=21"
scrolling="no" frameborder="0" style="border:none;
overflow:hidden; width:200px; height:21px;"
allowTransparency="true"></iframe>
                    </div>
                </div>';
    }
    return $content;
}
add_action('the_content', 'share_this');

Track WordPress Post Views by Using Post Meta

For a simple way to keep track of the number of post views, paste this snippet into the functions.php, and then follow steps 1 and 2.

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: Paste the code below within the single.php within the loop:

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

Step 2: Paste the snippet below anywhere within the template where you would like to display the number of views:

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

Track WordPress Post View Amount by Using Post Meta

This snippet will create a list of your most popular posts based on page views. Please note that this will only work if you have already implemented the ‘Track Post View Amount by Using Post Meta’ from above.
Place this snippet just before the loop within the index.php template and WordPress will use the post views to order your posts from highest to lowest.

<?
query_posts('meta_key=post_views_count&orderby=post_views_count&order=DESC');
?>

WordPress Breadcrumbs Without a Plugin

Breadcrumbs can be a useful navigation technique that offers link to the previous page the user navigated through to arrive at the current post/page. There are plugins you could use, but the code snippet below could be an easier solution.

Paste this code into your functions.php file.

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

Then paste the calling code below, wherever you would like the breadcrumbs to appear (typically above the title tag).

<?php the_breadcrumb(); ?>

Display the Number of Facebook Fans

Facebook is a must site for sharing your blogs articles. Here is a method for showing your visitors the total number of Facebook ‘Likes’ your blog currently has.

To use this code all you have to do is replace the YOUR PAGE-ID with your own Facebook page id.

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

Display an External RSS Feed in WordPress

This snippet will fetch the latest entries of any specified feed url.

<?php include_once(ABSPATH.WPINC.'/rss.php');
wp_rss('http://wpforums.com/external.php?type=RSS2', 5); ?>

This code takes the rss.php file that is built into WordPress (used for widgets). It is set to display the most recent 5 posts from the RSS feed ‘http://example.com/external.php?type=RSS2’.

WordPress Shortcode to Display External Files

If you are looking for a quick way to automatically include external page content within your post, this snippet will create a shortcode allowing you to do it.

Paste this code into your themes functions.php file:

function show_file_func( $atts ) {
  extract( shortcode_atts( array(
    'file' => ''
  ), $atts ) );
 
  if ($file!='')
    return @file_get_contents($file);
}
 
add_shortcode( 'show_file', 'show_file_func' );

And then post this shortcode, editing the URL, into your post or page.

[show_file file="https://speckyboy.com/2010/12/09/20-plugin-replacing-tutorials-tips-snippets-and-solutions-for-wordpress/"]

Create Custom WordPress Widgets

WordPress provides many widgets, but if you want to create custom widgets tailored to your blog, then this snippet may help you.

Paste the code below into your functions.php file.

    class My_Widget extends WP_Widget {  
        function My_Widget() {  
            parent::WP_Widget(false, 'Our Test Widget');  
        }  
    function form($instance) {  
            // outputs the options form on admin  
        }  
    function update($new_instance, $old_instance) {  
            // processes widget options to be saved  
            return $new_instance;  
        }  
    function widget($args, $instance) {  
            // outputs the content of the widget  
        }  
    }  
    register_widget('My_Widget'); 
	

Create Custom WordPress Shortcodes

Shortcodes are a handy way of using code functions within your theme. The advantage of shortcodes is that they can be easily used with the WordPress post editor.

Add this code to your functions.php:

function helloworld() {
return 'Hello World!';
}
add_shortcode('hello', 'helloworld');

You can then use [hello] wherever you want to display the content of the shortcode.

Custom Title Length

This snippet will allow you to customise the length (by the number of characters) of your post title.

Paste this code into the functions.php:

    
function ODD_title($char)
    {
    $title = get_the_title($post->ID);
    $title = substr($title,0,$char);
    echo $title;
    }

To use this function all you have to do is paste the below code into your theme files, remembering to change the ’20’ to what ever character amount you require:

<?php ODD_title(20); ?>

Custom WordPress Excerpts

Sometimes you may need to limit how many words are in the excerpt, with this snippet you can create your own custom excerpt (my_excerpts) replacing the original.

Paste this code in functions.php.

    
<?php add_filter('the_excerpt', 'my_excerpts');
function my_excerpts($content = false) {
            global $post;
            $mycontent = $post->post_excerpt;
 
            $mycontent = $post->post_content;
            $mycontent = strip_shortcodes($mycontent);
            $mycontent = str_replace(']]>', ']]&gt;', $mycontent);
            $mycontent = strip_tags($mycontent);
            $excerpt_length = 55;
            $words = explode(' ', $mycontent, $excerpt_length + 1);
            if(count($words) > $excerpt_length) :
                array_pop($words);
                array_push($words, '...');
                $mycontent = implode(' ', $words);
            endif;
            $mycontent = '<p>' . $mycontent . '</p>';
// Make sure to return the content
    return $mycontent;
}
?>

Secondly, paste this code within the Loop:

<?php echo my_excerpts(); ?>

Redirect WordPress Post Titles To External Links

This snippet could be useful for anyone with a news submission site, by redirecting your post title to an external URL when clicked via a custom field.

Paste this snippet into your functions.php file:

//Custom Redirection
function print_post_title() {
global $post;
$thePostID = $post->ID;
$post_id = get_post($thePostID);
$title = $post_id->post_title;
$perm  = get_permalink($post_id);
$post_keys = array(); $post_val  = array();
$post_keys = get_post_custom_keys($thePostID);
if (!empty($post_keys)) {
foreach ($post_keys as $pkey) {
if ($pkey=='url') {
$post_val = get_post_custom_values($pkey);
}
}
if (empty($post_val)) {
$link = $perm;
} else {
$link = $post_val[0];
}
} else {
$link = $perm;
}
echo '<h2><a href="'.$link.'" rel="bookmark" title="'.$title.'">'.$title.'</a></h2>';
}

Then you add a custom field named ‘url’ and in the value field put the link to which the title is to be redirected to.

Redirect to Single WordPress Post if There is Only One Post in Category/Tag

If there is only one post within a category or tag, this little snippet will jump the reader directly to the post page.

Paste this code into your themes functions.php file:

function stf_redirect_to_post(){
    global $wp_query;
 
    // If there is one post on archive page
    if( is_archive() && $wp_query->post_count == 1 ){
        // Setup post data
        the_post();
        // Get permalink
        $post_url = get_permalink();
        // Redirect to post page
        wp_redirect( $post_url );
    }  
 
} add_action('template_redirect', 'stf_redirect_to_post');

List Scheduled/Future WordPress Posts

Paste the code anywhere on your template where you want your scheduled posts to be listed, changing the max number or displayed posts by changing the value of showposts in the query.

<?php
$my_query = new WP_Query('post_status=future&order=DESC&showposts=5');
if ($my_query->have_posts()) {
    while ($my_query->have_posts()) : $my_query->the_post();
        $do_not_duplicate = $post->ID; ?>
        <li><?php the_title(); ?></li>
    <?php endwhile;
}
?>

Screenshots of External WordPress Pages Without a Plugin

This is a very simple URL script that will generate a screenshot of any website. Here is the URL:

http://s.wordpress.com/mshots/v1/http%3A%2F%2Fspeckyboy.com%2F?w=500

To see what the link above does, click here.

All you have to do is insert your required URL in the place of the ‘speckyboy.com’ part of the link and resize (‘w=500’) as required.

Add Content to the End of Each RSS Post

Adding some extra content that is only viewable by your RSS subscribers couldn’t be easier with this snippet.
Paste this code into the functions.php:

function feedFilter($query) {
    if ($query->is_feed) {
        add_filter('the_content','feedContentFilter');
    }
    return $query;
}
add_filter('pre_get_posts','feedFilter');
 
function feedContentFilter($content) {
    $content .= '<p>Extra RSS content goes here... </p>';
 
    return $content;
}

Reset Your WordPress Password

What would you do if you forget your WordPress Admin Password and you no longer have access to the admin area? To fix this all you have to do is jump to your PhpMyAdmin Sql-window and run the following command.

UPDATE `wp_users` SET `user_pass` = MD5('NEW_PASSWORD') WHERE `wp_users`.`user_login` =`YOUR_USER_NAME` LIMIT 1;

Detect Which Browser Your WordPress Visitors are Using

If you want to use different stylesheets for different browsers, then this is a snippet you could use. It detects the browser your visitors are using and creates a different class for each browser. You can use that class to create custom stylesheets.

add_filter('body_class','browser_body_class');
function browser_body_class($classes) {
global $is_lynx, $is_gecko, $is_IE, $is_opera, $is_NS4, $is_safari, $is_chrome, $is_iphone;
if($is_lynx) $classes[] = 'lynx';
elseif($is_gecko) $classes[] = 'gecko';
elseif($is_opera) $classes[] = 'opera';
elseif($is_NS4) $classes[] = 'ns4';
elseif($is_safari) $classes[] = 'safari';
elseif($is_chrome) $classes[] = 'chrome';
elseif($is_IE) $classes[] = 'ie';
else $classes[] = 'unknown';
if($is_iphone) $classes[] = 'iphone';
return $classes;
}

Display WordPress Search Terms from Google Users

If a visitor reached your site through Google’s search, this script will display the terms they searched for in order to find your site. Just paste it anywhere outside of the header section.

<?php
$refer = $_SERVER["HTTP_REFERER"];
if (strpos($refer, "google")) {
        $refer_string = parse_url($refer, PHP_URL_QUERY);
        parse_str($refer_string, $vars);
        $search_terms = $vars['q'];
        echo 'Welcome Google visitor! You searched for the following terms to get here: ';
        echo $search_terms;
};
?>

Show Different Content for Mac & Windows

If you ever have the need to display different content to either Mac or Windows users (ie. software download link for different platforms), you can paste the following code into your themes functions.php file. You can easily change the content of the function to your own needs.

<?php
if (stristr($_SERVER['HTTP_USER_AGENT'],"mac")) {
echo ‘Hello, I\’m a Mac.’;
} else {
echo ‘And I\’m a PC.’;
}
?>

Top
This page may contain affiliate links. At no extra cost to you, we may earn a commission from any purchase via the links on our site. You can read our Disclosure Policy at any time.