13 Useful Code Snippets for WordPress Development

By / Dec 28, 2009 / Tips
shares

WordPress has grown to be commonly defined as the core solution for your blogging needs. It is the most recognized and sought after Content Management System by writers and designers. Consequently, over the past few years there has been a voluble increase in WordPress blogs, this has caused the “need” for useful tips, tricks, and hacks, all made to allow the customizing of your WordPress powered site. Here are 13 code snippets or hacks that will help you extend the capabilities of your WordPress site.

Customize the Logo of Your WordPress Login Page

After constantly having to visit your WordPress login page, having to see the same logo and design over and over can be a bit boring. This is where this hack comes in handy. All you have to do is place the following in your functions.php file, and replace the image.


function my_custom_login_logo() {
    echo '<style type="text/css">
        h1 a { background-image:url('.get_bloginfo('template_directory').'/images/custom-login-logo.gif) !important; }
    </style>';
}

add_action('login_head', 'my_custom_login_logo');

Source

Detecting Mobile Devices Accessing Your Site

Mobile web surfing is continuing to evolve on a larger scale. This is why detecting those users who are visiting your WordPress blog through a mobile device and redirecting them to a mobile version of your site is important. In order to achieve this, you first have to get the code from detectmobilebrowsers.mobi and upload it to your theme directory.

Then, all you simply have to do is open your header.php file and place the following at the top of the file. Remember to edit line 5 to where you’d like to redirect mobile users.


include('mobile_device_detect.php');
$mobile = mobile_device_detect();

if ($mobile==true) {
  header( 'Location: http://your-website.com/?theme=Your_Mobile_Theme' ) ;
}

Source

Automatically Resize Images

If you’re accustomed to displaying large quantities of images on your blog, then you know how tedious it can be to have to always resize your images manually. Now you can use this hack to automatically resize any image you’d like to whatever width and height you choose for a more organized look. To do this, copy the following script and create a folder for it anywhere on your site (i.e. scripts) and name it “timthumb.php“. Now, you can use the following syntax to add an automatically resized image to your blog post:


<img src="/scripts/timthumb.php?src=/images/whatever.jpg&amp;h=150&amp;w=150&amp;zc=1" alt="" />

Direct Source

Displaying Your Tags in a Dropdown Menu

Tag clouds are often hard to read, especially for a more busy site. Eliminate this problem by using a dropdown menu to display your tags. You must place the following code in your functions.php file.


<?php
function dropdown_tag_cloud( $args = '' ) {
	$defaults = array(
		'smallest' => 8, 'largest' => 22, 'unit' => 'pt', 'number' => 45,
		'format' => 'flat', 'orderby' => 'name', 'order' => 'ASC',
		'exclude' => '', 'include' => ''
	);
	$args = wp_parse_args( $args, $defaults );

	$tags = get_tags( array_merge($args, array('orderby' => 'count', 'order' => 'DESC')) ); // Always query top tags

	if ( empty($tags) )
		return;

	$return = dropdown_generate_tag_cloud( $tags, $args ); // Here's where those top tags get sorted according to $args
	if ( is_wp_error( $return ) )
		return false;
	else
		echo apply_filters( 'dropdown_tag_cloud', $return, $args );
}

function dropdown_generate_tag_cloud( $tags, $args = '' ) {
	global $wp_rewrite;
	$defaults = array(
		'smallest' => 8, 'largest' => 22, 'unit' => 'pt', 'number' => 45,
		'format' => 'flat', 'orderby' => 'name', 'order' => 'ASC'
	);
	$args = wp_parse_args( $args, $defaults );
	extract($args);

	if ( !$tags )
		return;
	$counts = $tag_links = array();
	foreach ( (array) $tags as $tag ) {
		$counts[$tag->name] = $tag->count;
		$tag_links[$tag->name] = get_tag_link( $tag->term_id );
		if ( is_wp_error( $tag_links[$tag->name] ) )
			return $tag_links[$tag->name];
		$tag_ids[$tag->name] = $tag->term_id;
	}

	$min_count = min($counts);
	$spread = max($counts) - $min_count;
	if ( $spread <= 0 )
		$spread = 1;
	$font_spread = $largest - $smallest;
	if ( $font_spread <= 0 )
		$font_spread = 1;
	$font_step = $font_spread / $spread;

	// SQL cannot save you; this is a second (potentially different) sort on a subset of data.
	if ( 'name' == $orderby )
		uksort($counts, 'strnatcasecmp');
	else
		asort($counts);

	if ( 'DESC' == $order )
		$counts = array_reverse( $counts, true );

	$a = array();

	$rel = ( is_object($wp_rewrite) && $wp_rewrite->using_permalinks() ) ? ' rel="tag"' : '';

	foreach ( $counts as $tag => $count ) {
		$tag_id = $tag_ids[$tag];
		$tag_link = clean_url($tag_links[$tag]);
		$tag = str_replace(' ', '&nbsp;', wp_specialchars( $tag ));
		$a[] = "\t<option value='$tag_link'>$tag ($count)</option>";
	}

	switch ( $format ) :
	case 'array' :
		$return =& $a;
		break;
	case 'list' :
		$return = "<ul class='wp-tag-cloud'>\n\t<li>";
		$return .= join("</li>\n\t<li>", $a);
		$return .= "</li>\n</ul>\n";
		break;
	default :
		$return = join("\n", $a);
		break;
	endswitch;

	return apply_filters( 'dropdown_generate_tag_cloud', $return, $tags, $args );
}
?>

Now, to finalize your dropdown menu you have to open the theme file where you want the list to be displayed (i.e. sidebar.php) and insert the following code:


<select name="tag-dropdown" onchange="document.location.href=this.options[this.selectedIndex].value;">
	<option value="#">Liste d'auteurs</option>
	<?php dropdown_tag_cloud('number=0&order=asc'); ?>
</select>

Source

Custom “Read More” Links for Your Posts

This is a really useful hack if you want to better define or customize the look of your “Read More” links for posts. The first thing you have to do is to edit your posts and create custom fields. Give them custom_more as a key, and whatever text you want to be displayed as the value. Then you have to edit your index.php file (and also your category.php, search.php, etc) and find a line similar to this:


the_content("Read more");

Now just replace it with this code:


<?php $custommore = get_post_meta($post->ID, 'custom_more', true); ?>
<?php if (!$custommore) { $custommore = 'Read More &raquo;'; } ?>
<?php the_content($custommore); ?>

Source

Scheduling Posts for RSS

If you regularly publish articles and you care about the quality of your posts then this is a good hack for you. The main purpose of this hack is that it lets you schedule your posts to be viewed in your RSS at a later time, this will allow you enough time to get those last minute fixes and additions in before your post is forever published in your feed. Place the following code in your .htaccess file. In order to change the length of the delay, change the value of the $waitvariable on line 9.


function publish_later_on_feed($where) {
	global $wpdb;

	if ( is_feed() ) {
		// timestamp in WP-format
		$now = gmdate('Y-m-d H:i:s');

		// value for wait; + device
		$wait = '5'; // integer

		// http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_timestampdiff
		$device = 'MINUTE'; //MINUTE, HOUR, DAY, WEEK, MONTH, YEAR

		// add SQL-sytax to default $where
		$where .= " AND TIMESTAMPDIFF($device, $wpdb->posts.post_date_gmt, '$now') > $wait ";
	}
	return $where;
}

add_filter('posts_where', 'publish_later_on_feed');

Source

Display the Most Commented Posts of 2009

As the New Year is about to role in, it would be fun and resourceful to let your readers know which of your posts were most popular in the past year. This hack will allow your visitors to view the top 10 most commented/popular posts of 2009. This is a great way to give your posts a second shot at being noticed. In order to do this, you’ll need to place the following code on your sidebar.php file, or wherever else you’d like on your theme:


<ul>
<?php
$result = $wpdb->get_results("SELECT comment_count,ID,post_title, post_date FROM $wpdb->posts WHERE post_date BETWEEN '2009-01-01' AND '2009-12-31' ORDER BY comment_count DESC LIMIT 0 , 10");

foreach ($result as $topten) {
    $postid = $topten->ID;
    $title = $topten->post_title;
    $commentcount = $topten->comment_count;
    if ($commentcount != 0) {
    ?>
         <li></li>
    <?php }
}
?>
</ul>

Source

Allow Only Your IP Address to Access the wp-admin Directory

If you don’t have multiple writers or contributors to your blog, then realistically speaking only you should be allowed to visit the wp-admin directory. Especially since a great deal of security risks entail the wp-admin directory. All you have to do is enter your static IP adress on line 8. You can add more IPs if needed, by creating a new line. Place the following in your .htaccess file.


AuthUserFile /dev/null
AuthGroupFile /dev/null
AuthName "Example Access Control"
AuthType Basic
<LIMIT GET>
order deny,allow
deny from all
allow from xx.xx.xx.xx
</LIMIT>

Source

Styling Your WordPress Comments

When your blog has lots of comments, then it’s a great way to get visitors to interact more by styling the way your comments are displayed. If this is what you’re looking to to, then open your comments.php file and replace your comments loop with the following code:


<ol id="commentlist">
<?php foreach ($comments as $comment) : ?>
	<?php // The extra stuff to get commenter's role
	$user_id = $comment->user_id;
	$role = ( isset( $roles[$user_id] ) ? $roles[$user_id] : '' );
	?>
	<li class="<?php echo $role; ?>">
	<p>By <?php comment_author_link() ?> - <?php comment_date() ?></p>
	<?php comment_text() ?>
	</li>
<?php endforeach; ?>
</ol>

Now to structure your comment you’ll need to open your style.css file and place the following code:


#commentlist li { border:2px solid white; } /* not logged or subscriber */
#commentlist li.administrator { border:2px solid red } /* blog admin */
#commentlist li.editor { border:2px solid blue } /* editor */

Source

Remove Widget Areas on Your Homepage

If your WordPress powered site is more than just a blog, then you probably want to get rid of the widget areas in your default sidebar and create your own. This hack doesn’t require any editing, just code insertion. Now, all you need to do is add the following to your functions.php file:


<?php
add_filter( 'sidebars_widgets', 'disable_all_widgets' );

function disable_all_widgets( $sidebars_widgets ) {
	if ( is_home() )
		$sidebars_widgets = array( false );
	return $sidebars_widgets;
}
?>

Source

Insert Author Bio for Each Post

A multi-writer blog usually means everyone who writes or contributes a post will have section that speaks about them. If your blog doesn’t have this feature, then 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

Remove Certain Categories From Being Displayed

Place this code inside The Loop and whichever category you choose, it will not be displayed. This can be an interesting hack for those who only wish to display a certain category to chosen or registered users.


<?php
if ( have_posts() ) : query_posts($query_string .'&cat=-1,-2'); while ( have_posts() ) : the_post();
?>

Source

Redirect Your WordPress Feed to FeedBurner

If you’ve found out how useful FeedBurner really is after you’ve set-up your WordPress site, and you have a few RSS subscribers on your default WordPress feed, then you’ll need to redirect your feed to FeedBurner. Every time a user follows a link to your default feed (i.e. http://www.yourblog.com/feed) they will be redirected to the location of your FeedBurner feed ( i.e. http://feeds.feedburner.com/yourblog). This way, even if a user manages to somehow subscribe to your old RSS feed, they will always be redirected to your new feed. Place the following code in your .htaccess file.


# temp redirect wordpress content feeds to feedburner
<IfModule mod_rewrite.c>
 RewriteEngine on
 RewriteCond %{HTTP_USER_AGENT} !FeedBurner    [NC]
 RewriteCond %{HTTP_USER_AGENT} !FeedValidator [NC]
 RewriteRule ^feed/?([_0-9a-z-]+)?/?$ http://feeds.feedburner.com/WebDesignLedger [R=302,NC,L]
</IfModule>

Source

26 Comments

  1. Jon
    December 28, 2009

    Great article! This one will come in handy, without a doubt!

    Reply
  2. Brendan Wenzel
    December 28, 2009

    Thank you very much for sharing this list of snippets. I’m actually creating my own theme right now and this post was perfectly timed. I love this site so much.

    Reply
  3. Jouni
    December 28, 2009

    Hi guys, I hope you don’t mind that I added a Finnish version of the Feedburner tip to my blog:

    http://mutaati0.com/ohjaa-rss-feedi-feedburneriin

    My article contains a link back to this article :)

    Reply
  4. Ozh
    December 28, 2009

    First code snippet won’t work as it uses an external script (timthumb or whatever) that you don’t link to.

    Didn’t read further.

    Reply
    • Joel Reyes
      December 28, 2009

      Hi Ozh

      I apologize for the mix-up, I’ve managed to fix it :)

      Thank you for pointing it out…

      Reply
  5. Heiko
    December 28, 2009

    Great tips – I like the mobile detection tool, should be integrated in wordpress by default.
    cheers

    Reply
  6. Blogger Den
    December 28, 2009

    I haven’t done much WordPress development, but I’m eager to get into it! I know there’s a lot to make with WordPress and designs are so easily customizable it’s insane

    Reply
  7. Alex Flueras
    December 29, 2009

    Really useful article. Bookmarked. Thanks for sharing.

    Reply
  8. Marcell Purham
    December 29, 2009

    Great snippet of code. Very useful thanks!

    Reply
  9. Indrek
    December 29, 2009

    Thanks Joel for a great list!
    Actually I found quite a few that I’m going to try and implement to get rid of a few plugins that do the same work.

    Reply
  10. Web Design by 314media.com St. Louis
    December 29, 2009

    All good stuff … No core editing on those snippets, so good stuff – Cheers!

    Reply
  11. Noel Wiggins
    December 29, 2009

    The custom logo and comments styled snippets are the greatest! Can’t wait to try em

    Thanks and Regards

    Noel for Nopun.com
    a graphic design studio

    Reply
  12. michelle
    December 31, 2009

    these are great thank you, I am going to give the custom comments section a try now :)

    Reply
  13. Dave
    December 31, 2009

    This is great – I love the one to display the most commented posts of 2009. It wouldn’t be much work to make it display the most commented posts of the previous year (or current year once you hit December) – then it would be something you could leave up all the time.
    I really link the tip to redirect your rss feed to feedburner – that’s a really cool way to do it using your .htaccess instead of modifying wordpress. Feedburner has some great features for massaging your RSS feed, getting stats, and even adding advertising.

    Reply
  14. Wordpress Development
    January 15, 2010

    what a collection of snippets… all running very much smoothly…
    I think this post has made a significant increase in my productivity….

    ThanX guyz..

    Reply
  15. Konstantin
    January 18, 2010

    Nice list. Some of them pretty obvious, but others may be trivial to some people ;) Thanks!

    ~ K.

    Reply
  16. Xander
    February 12, 2010

    Nice article. Thank you for sharing.

    Reply
  17. GDevelop WebDesign
    March 2, 2010

    Thanks for these list of useful code snippets.

    I don’t get a grip on the “delayed rss publication” snippet.
    Why should this snippet (function) be added to the .htaccess File?

    Reply
  18. ZOMGBananas
    March 17, 2010

    Nice and helpful, I can see I’ll be using a few of these things in my sites next incarnation. Cheers!

    Reply
  19. b2c
    April 18, 2010

    Great tips – I like the mobile detection tool, should be integrated in wordpress by default.
    cheers

    Reply
  20. Quantenphysiker
    April 28, 2010

    wow great snippets. Thanks a lot for sharin. I liked most the mobile detechtion tool.

    Reply
  21. Abhijit V. Chaore
    June 23, 2010

    I particularly liked the ‘Allow Only Your IP Address to Access the wp-admin Directory’ as it is good for security purpose. Thanks.

    Reply
  22. Aristo
    August 12, 2010

    Very Helpful..I was actually looking for the Author Bio snippet – Will give it a spin. Thanks!

    Reply
  23. Mick Gill
    August 18, 2010

    Great Article! Picked up a few good tips!

    Reply
  24. Muhammad Ghazali
    August 29, 2010

    Hei, great article, the collected code snippet is really helpful. Thank you.

    Reply
  25. Nilesh
    September 17, 2013

    Thanks for the mobile detect snippet. It helped me to redirect my websites mobile visitors to a mobile theme.

    Reply

Leave a Reply