• Blog

    Latest from our Blog

  • Tools

    Our Favourite WP Tools

  • Hosting

    Recommended Web Hosts

  • Coupons

    Get great money off deals

  • Themes

    WordPress Theme Directory

  • Plugins

    WordPress Plugins Directory

  • Promote

    Your WordPress Product

It helps when coding your own themes to have an array of code snippets to hand that you can incorporate into your the theme, I have collected a huge number of hacks and code snippets over the years which I will be sharing with you in this post, I hope you find them helpfull.

Conditional Tags

Conditional tags are very usefull as you can use them for things like a highlighted item in a nav menu, show a different css class depending which page you are on.

<ul id="nav">
  <li<?php if ( is_home() || is_category() || is_archive() || is_search() || is_single() || is_date() ) { echo ' class="current"'; } ?>><a href="#">Gallery</a></li>
  <li<?php if ( is_page('about') ) { echo ' class="current"'; } ?>><a href="#">About</a></li>
  <li<?php if ( is_page('submit') ) { echo ' class="current"'; } ?>><a href="#">Submit</a></li>
</ul>

Source: Web Designer Wall

Post Author Info Box

If you have a multi-author blog its nice to show some author info after the blog post. These tags will display various info about the post author, add them to your single.php file :

Author’s Gravatar

<?php echo get_avatar( get_the_author_email(), $size = '100' ); ?>

Author’s Website Link

<a href="<?php the_author_url(); ?>">Author’s Website</a>

Author’s About Me Info

<?php the_author_description(); ?>

Source: Tutorial Mag

Highlight Author’s Comments

This will allow you to apply different styling in the comments section to your own comments so they stand out from normal users:

Add this to your stylesheet :

.authcomment {
background-color: #B3FFCC !important;
}

Edit comments.php like so :

<li class=”<?php
/* Only use the authcomment class from style.css if the user_id is 1 (admin) */
if (1 == $comment->user_id)
$oddcomment = “authcomment”;
echo $oddcomment;
?>”

Source: Matt Cutts

Disable HTML in Comments

If you dont want people to be able to use the default HTML tags that are allowed in WordPress, add this code to your theme’s functions.php file:

// This will occur when the comment is posted
function plc_comment_post( $incoming_comment ) {

	// convert everything in a comment to display literally
	$incoming_comment['comment_content'] = htmlspecialchars($incoming_comment['comment_content']);

	// the one exception is single quotes, which cannot be #039; because WordPress marks it as spam
	$incoming_comment['comment_content'] = str_replace( "'", '&apos;', $incoming_comment['comment_content'] );

	return( $incoming_comment );
}

// This will occur before a comment is displayed
function plc_comment_display( $comment_to_display ) {

	// Put the single quotes back in
	$comment_to_display = str_replace( '&apos;', "'", $comment_to_display );

	return $comment_to_display;
}

add_filter( 'preprocess_comment', 'plc_comment_post', '', 1);
add_filter( 'comment_text', 'plc_comment_display', '', 1);
add_filter( 'comment_text_rss', 'plc_comment_display', '', 1);
add_filter( 'comment_excerpt', 'plc_comment_display', '', 1);

Source: Web Developer Plus

Display AdSense Ads to Search Engines Visitors Only

Search engine visitors are more likely to click on your adsense ads, so to preserve your CTR this is a great tip to use :

Place this code in your functions.php file:

function scratch99_fromasearchengine(){
  $ref = $_SERVER['HTTP_REFERER'];
  $SE = array('/search?', 'images.google.', 'web.info.com', 'search.', 'del.icio.us/search', 'soso.com', '/search/', '.yahoo.');
  foreach ($SE as $source) {
    if (strpos($ref,$source)!==false) return true;
  }
  return false;
}

Then add this in your theme where you want the adsense block to appear :

if (function_exists('scratch99_fromasearchengine')) {
  if (scratch99_fromasearchengine()) {
    INSERT YOUR CODE HERE
  }
}

Source: Smashing Magazine

Display an Advert after the first Post

Use this code in index.php to display an advert or Google Adsense after the first post :

<?php if (have_posts()) : ?>

<?php while (have_posts()) : the_post(); $loopcounter++; ?>

  // the loop stuffs

  <?php if ($loopcounter <= 1) { include (TEMPLATEPATH . '/ad.php'); } ?>

<?php endwhile; ?>

<?php else : ?>

<?php endif; ?>

Source: Web Designer Wall

Display Latest Posts

Use this code to display a list of your latest 5 posts, I like to use this in a footer or sidebar :

<?php query_posts('showposts=5'); ?>

<ul>
  <?php while (have_posts()) : the_post(); ?>
  <li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
  <?php endwhile;?>
</ul>

Source: Web Designer Wall

Show Scheduled Posts

If you have posts in upcoming que and wish to display them pubicly, use this code anywhere in your theme :

<code>
	<?php query_posts('showposts=10&post_status=future'); ?>
	<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

			<p class><b><?php the_title(); ?></b><?php edit_post_link('e',' (',')'); ?><br />

			<span class="datetime"><?php the_time('j. F Y'); ?></span></p>

	<?php endwhile; else: ?><p>No future posts scheduled.</p><?php endif; ?>

</div>

Source: Malar Vizhi

Show Most commented Posts with a thumbnail

A handy hack to use in your sidebar, your most popular posts rated by comment count. Paste the following code and change http://an-alternative-image.jpg to an image of your choice incase the post doesn’t have a thumbnail:

	<?php $popular = new WP_Query('orderby=comment_count&amp;posts_per_page=5'); ?>

<?php while ($popular->have_posts()) : $popular->the_post(); ?>

<?php $justanimage = get_post_meta($post->ID, 'Image', true);

if ($justanimage) { ?>

<img src="<?php echo get_post_meta($post-/>ID, "Image", true); ?>" alt="<?php the_title(); ?>" />

<?php } else { ?>

<img src="http://an-alternative-image.jpg" alt="" />

<?php } ?>

<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>

<?php endwhile; ?>

Source: The Mega Mag

Display your Feedburner count as text

Simple way to display your Feedburner subscriber count in text format, replace YOUR FEED ADDRESS with your own url:

<?php
$url = file_get_contents('https://feedburner.google.com/api/awareness/1.0/Get
FeedData?uri=YOUR FEED ADDRESS');
$begin = 'circulation="'; $end = '"';
$page = $url;
$parts = explode($begin,$page);
$page = $parts[1];
$parts = explode($end,$page);
$fbcount = $parts[0];
if($fbcount == '') { $fbcount = '0'; }
echo '<b> '.$fbcount.'  Subscribers';
?>

</div>

Source: The Mega Mag

Display your Twitter Follower Count as text

Simple way to display your Feedburner subscriber count in text format, replace USERNAME with your own username.

<?php
$twit = file_get_contents('http://twitter.com/users/show/USERNAME.xml');
$begin = '<followers_count>'; $end = '';
$page = $twit;
$parts = explode($begin,$page);
$page = $parts[1];
$parts = explode($end,$page);
$tcount = $parts[0];
if($tcount == '') { $tcount = '0'; }
echo '<b> '.$tcount.' </b> Followers';
?>
</div>

Source: The Mega Mag

Highlight Searched text in Search Results

A nice simple change that will highlight the text searched for on the search results page.

First of all open your search.php file and find the the_title() function and replace it with :

echo $title;

Now before the modified code, add this :

<?php
    $title     = get_the_title();
    $keys= explode(" ",$s);
    $title     = preg_replace('/('.implode('|', $keys) .')/iu',
        '<strong class="search-excerpt"></strong>',
        $title);
?>

Finally, add some styling in your stylesheet.css :

strong.search-excerpt { background: yellow; }

Source: Malar Vizhi

How To Separate Trackbacks from Comments

If you want to show trackbacks separately in your comments section then use the following :

Open comments.php and find the following :

<?php foreach ($comments as $comment) : ?>

After it, paste this :

<?php $comment_type = get_comment_type(); ?>
<?php if($comment_type == 'comment') { ?>

Now find :

<?php endforeach; /* end for each comment */ ?>

Before it, Paste :

<?php } else { $trackback = true; } /* End of is_comment statement */ ?>

That has now removed trackbacks and pingbacks, we just need to add a loop for them separately now, find the following :

<?php else : // this is displayed if there are no comments so far ?>

Before it, Paste :

<?php if ($trackback == true) { ?>
<h3>Trackbacks</h3>
<ol>
<?php foreach ($comments as $comment) : ?>
<?php $comment_type = get_comment_type(); ?>
<?php if($comment_type != 'comment') { ?>
<li><?php comment_author_link() ?></li>
<?php } ?>
<?php endforeach; ?>
</ol>
<?php } ?>

Source: Pro Blog Design

Add a login box to your theme

If you want to let people login from your website without going to the WordPress login page, you can paste the following code where you want the loginbox, for example in your sidebar :

	<li>
		<?php global $user_ID, $user_identity, $user_level ?>
		<?php if ( $user_ID ) : ?>
		<h2>Control panel</h2>
		<ul>
			<li>Identified as <strong><?php echo $user_identity ?></strong>.
			<ul>
				<li><a href="<?php bloginfo('url') ?>/wp-admin/">Dashboard</a></li>
				<?php if ( $user_level >= 1 ) : ?>
				<li><a href="<?php bloginfo('url') ?>/wp-admin/post-new.php">Write an article</a></li>
				<?php endif // $user_level >= 1 ?>
				<li><a href="<?php bloginfo('url') ?>/wp-admin/profile.php">Profile and personal options</a></li>
				<li><a href="<?php bloginfo('url') ?>/wp-login.php?action=logout&amp;redirect_to=<?php echo urlencode($_SERVER['REQUEST_URI']) ?>">Exit</a></li>
			</ul>
			</li>
		</ul>
		<?php elseif ( get_option('users_can_register') ) : ?>
		<h2>Identification</h2>
		<ul>
			<li>
			<form action="<?php bloginfo('url') ?>/wp-login.php" method="post">
				<p>
				<label for="log"><input type="text" name="log" id="log" value="<?php echo wp_specialchars(stripslashes($user_login), 1) ?>" size="22" /> User</label><br />
				<label for="pwd"><input type="password" name="pwd" id="pwd" size="22" /> Password</label><br />
				<input type="submit" name="submit" value="Send" class="button" />
				<label for="rememberme"><input name="rememberme" id="rememberme" type="checkbox" checked="checked" value="forever" /> Remember me</label><br />
				</p>
				<input type="hidden" name="redirect_to" value="<?php echo $_SERVER['REQUEST_URI']; ?>"/>
			</form>
			</li>
			<li><a href="<?php bloginfo('url') ?>/wp-register.php">Register</a></li>
			<li><a href="<?php bloginfo('url') ?>/wp-login.php?action=lostpassword">Recover password</a></li>
		</ul>
		<?php endif // get_option('users_can_register') ?>
	</li>

Source: WP Designer

Exclude a category from the homepage

Really handy hack, if you wanted to use a category for news in your sidebar etc In this code, the category number excluded is 7 :

<?php while ( have_posts() ) {
the_post();
if (is_home()) if (in_category('7')) continue;
?>

Source: Designer Daily

Exclude a category from the RSS Feed

For the same reason, you may to exclude this category from your RSS Feed, again the category excluded is 7 :


http://www.yoururl.com/feed?cat=-7

Source: Designer Daily

Display posts from one category in the Sidebar

Now that you have excluded the category from the homepage and feed, you can include it on its own in the sidebar with the following code :

<?php query_posts('cat=7&showposts=10'); ?>
<?php while (have_posts()) : the_post(); ?> <a href="<?php the_permalink(); ?>>
<?php the_title(); ?></a><br />
<?php endwhile;?>

Source: Designer Daily

Display an external RSS Feed anywhere in your theme

If you want to include any RSS feed in your theme, use the following :

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

Source: Designer Daily

Add a Shortcode

Shortcodes are a simple way of inserting code functions in your theme without having to type them out each time, add this to your theme functions.php :

# Adds a shortcode called 'hello'.
function helloworld() {
  return 'Hello World!';
}
add_shortcode('hello', 'helloworld');

Then, where you want the fucntion to appear, type :

[hello]

Source: WP Snippets

Display “Time Ago” like Twitter

You can use this snippet for posts/pages or comments :

For Posts and Pages :

<?php echo human_time_diff(get_the_time('U'), current_time('timestamp')) . ' ago'; ?>

For Comments :

<?php echo human_time_diff(get_comment_time('U'), current_time('timestamp')) . ' ago'; ?>

Source: WP Snippets

Share on Facebook

Allow visitors to quickly share your post on facebook :

<a href="http://www.facebook.com/sharer.php?u=<?php the_permalink();?>&t=<?php the_title(); ?>" title="Share on Facebook" target="blank">Share on Facebook</a>

Source: WP Snippets

Empty the Trash Automatically

Handy little hack to auto-clear the trash, just add this to your wp-config.php file :

define('EMPTY_TRASH_DAYS', 5 );

Source: WP Snippets


Post Tags

Author:

Oliver Dale is the founder of Kooc Media, a small internet company based in the UK. Kooc Media runs several high-profile websites including WPLift, ThemeFurnace and DesignersTalk.

Leave Yours +

5 Comments

  1. Your facts furthermore suggestions identical nearby to my
    opinion. Thanks exceptionally significantly ahead of time.
    The know-how on this area is great, I’m glad with the purpose of here’s noticed.
    Thanks all over again!

Leave a Reply

* Required Fields.
Your email will not be published.

Search

Our Sponsors