wordpresstipsandtricks

25 WordPress Tips and Tricks to Make Your Theme Awesome

January 31, 2010 in Wordpress by Paul D'Amora

WordPress is an incredibily powerful and widely used CMS (Content Management System).  There are an endless numbers of things you can accomplish with it.  Of course, many of these things aren’t as well known as they should be, and we …

WordPress is an incredibily powerful and widely used CMS (Content Management System).  There are an endless numbers of things you can accomplish with it.  Of course, many of these things aren’t as well known as they should be, and we theme makers and site owners end up doing things the hard way.  How many of you opened up footer.php and changed the copyright date in the last few days?   How many of you didn’t?  These are simple things that you shouldn’t be wasting you precious brain power and time doing on your own, plus they add some coolness to your overall theme.  Not to mention just how much easier it makes your life.  Well, I’m going to show you TWENTY-FIVE of the very best tips and tricks around that YOU can easily implement into your theme.

1.  Automatically display the copyright date

Well, I already mentioned this one so I might as well start off with it.  We just began 2010 and you know what that means, time to change those copyright dates.  Yes, go ahead and edit that date while mine changes automatically on the stroke of 12.  This can be accomplished with a simple code.

Copyright &copy; 200x-<?php echo date('Y'); ?> Example.com.

If you want to automatically display your copyright date as a range of dates (2008-2010), check out this awesome post on DigWP.

2. Display a List of Allowed HTML Tags

WordPress doesn’t allow a lot of HTML tags in comments. But your commentators may not know that, well now they will.

You may use: <?php echo allowed_tags(); ?>.

3. Display Related Posts By Tags

There’re a whole slew of plugins out there that will display related posts. In case you want to do it without a plugin, here’s how.

<?php
//for use in the loop, list 5 post titles related to first tag on current post
$backup = $post;  // backup the current object
$tags = wp_get_post_tags($post->ID);
echo "<div><h3>Related Posts</h3>";
	$tagIDs = array();
	if ($tags)
	{
		$tagcount = count($tags);
			for ($i = 0; $i < $tagcount; $i++) {
			$tagIDs[$i] = $tags[$i]->term_id;
			}
			$args=array(
			'tag__in' => $tagIDs,
			'post__not_in' => array($post->ID),
			'showposts'=>5,
			'caller_get_posts'=>1
			);
			$my_query = new WP_Query($args);
			if( $my_query->have_posts() )
			{
			echo "<ul>";
			while ($my_query->have_posts()) : $my_query->the_post(); ?>
			<li><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a></li>
			<?php endwhile;
			echo "</ul>";
			}
	} else echo "<span>No related posts were found!</span>";
	$post = $backup;  // copy it back
	wp_reset_query(); // to use the original query again
echo "</div>";
?>

4. Display Related Posts by Category

Depending on your type of blog, you may want to display your related posts based on the category of that actual post. Although, in my opinion tags would be more accurate, some people (myself included) don’t use tags.

<?php
$categories = get_the_category($post->ID);
if ($categories) {
	$category_ids = array();
	foreach($categories as $individual_category) $category_ids[] = $individual_category->term_id;

	$args=array(
		'category__in' => $category_ids,
		'post__not_in' => array($post->ID),
		'showposts'=>5, // Number of related posts that will be shown.
		'caller_get_posts'=>1
	);
	$my_query = new wp_query($args);
	if( $my_query->have_posts() ) {
		echo '<h3>Related Posts</h3><ul>';
		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
		}
		echo '</ul>';
	}
}
?>

5. Disable Commenting on Posts Older than One Month

If you write a REALLY good post on your blog, chances are it’ll be getting comments for quite some time. Maybe months later, people will still be talking actively about just how awesome of a post it was. That’s great and all, but there’s a certain point when you don’t have time to continuously moderate the comments on some of your older posts with new ones being made daily. This code will automatically disable the commenting function after some time. Paste it into your functions.php file ( Note – to change the number of days it will take to disable, just change the number 30)

<?php
function close_comments( $posts ) {
	if ( !is_single() ) { return $posts; }
	if ( time() - strtotime( $posts[0]->post_date_gmt ) > ( 30 * 24 * 60 * 60 ) ) {
		$posts[0]->comment_status = 'closed';
		$posts[0]->ping_status    = 'closed';
	}
	return $posts;
}
add_filter( 'the_posts', 'close_comments' );
?>

6. Place an “Edit” link next to each post.

This makes the lives of admins a whole lot easier. Just place this code somewhere within the Loop and it will automatically place an “Edit” link next to each post, that is only visible to admins.

<?php edit_post_link('Edit', ''); ?>

7. Include Your 404 Page

In the Loop of your themes, you probably have something like this -

<?php endwhile; ?>
<?php else : ?>
<404 TEXT HERE>
<?php endif; ?>

This is normally text to display if there are no posts. Instead of repeating this text on your index.php, single.php, search.php, ect… You can just put in your 404.php file, and replace the text after the “else” with

<?php include('404.php');?>

8. Display Popular Posts

A helpful list for visitors is to display the posts that other visitors supposedly liked. If 200 other people liked it enough to comment, chances are they will too. Try out this bit of code to display this information, make sure you put it in the functions.php file.

/*For Popular Posts*/
function popularPosts($num) {
    global $wpdb;
    $posts = $wpdb->get_results("SELECT comment_count, ID, post_title FROM $wpdb->posts ORDER BY comment_count DESC LIMIT 0 , $num");
    foreach ($posts as $post) {
        setup_postdata($post);
        $id = $post->ID;
        $title = $post->post_title;
        $count = $post->comment_count;
        if ($count != 0) {
            $popular .= '<li>';
            $popular .= '<a href="' . get_permalink($id) . '" title="' . $title . '">' . $title . '</a> ';
            $popular .= '</li>';
        }
    }
    return $popular;
}
/*End of Popular Posts*/

To output the results, paste the following code into your theme. The number 10 can be changed to fit the number of posts you would like to show.

<?php echo popularPosts(10); ?>

9. Show a “Tweet This” link

With the growing popularity of Twitter, it’s an opportunity you simply can’t miss out on. Putting a simple link at the end of each post could lead to quite a bit more traffic.

<a href="http://twitter.com/home?status=I just read <?php the_permalink(); ?>" title="Send this page to Twitter!" target="_blank">Tweet This!</a>

10. Show a Send to Facebook Link

Just like Twitter, facebook offers a lot of exposure and traffic. Don’t believe me? Try it out for yourself with this code -

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

11. Widgettize Your Sidebar

Widgets are a dynamic and quick way to update content in your sidebar and footer.
Just put the following code in your functions.php file -

/*For Sidebar Widget*/

if ( function_exists('register_sidebar') )
register_sidebar(array(
'name' => 'sidebar',
'before_widget' => '<div class="box">',
'after_widget' => '</div><!--.box-->',
'before_title' => '<h3>',
'after_title' => '</h3>',
));
/*End of For Sidebar Widget*/

Then, wherever you want your widgets to appear, put this

<?php if ( function_exists('dynamic_sidebar') && dynamic_sidebar(1) ) : else:  ?>
				<?php endif; ?>

12. List the Author’s Bio

On multi authored blogs you may want to list a bit of information about the author of a post. This information can easily be edited via the WP admin panel, and can easily be used via this code

<?php the_author_description(); ?>

13. Adding a Print Button to your Posts

While this is arguably redundant to built-in browser functions, some people might find it useful. It’s also worth mentioning it’s not a WordPress only trick, so all of you poor non-wordpress users get to have fun with it too.

<a href="javascript:window.print()">Print this Article</a>

14. Display Schedule Posts

Scheduling posts can help create a consistency of publish time for readers. Chances are, you don’t want to wake up at 5:00 AM to publish a post, but maybe your loyal foreign readers like to check their favorite blogs around lunchtime.

Well, with this code, you can also help create some suspense ahead of time.


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

        <?php the_title(); ?>

    <?php endwhile;

}

?>

15. How to Exclude Subpages in the Nav

For whatever reason, you may want to exclude subpages when showing the navigation for your WordPress theme.

<?php wp_list_pages (array ( 'depth' => 1, 'title_li' => _ _('')))?>

Note – This also discards the “Pages:” text that would normally precede the actual list of pages.

16.  Display Recent Comments

If you want to display the most recent comments on your blog, simply paste the following code into your functions.php file.


<?php
function recent_comments($src_count=10, $src_length=60, $pre_HTML='<ul>', $post_HTML='</ul>') {
global $wpdb;
$sql = "SELECT DISTINCT ID, post_title, post_password, comment_ID, comment_post_ID, comment_author, comment_date_gmt, comment_approved, comment_type,
SUBSTRING(comment_content,1,$src_length) AS com_excerpt FROM $wpdb->comments LEFT OUTER JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID = $wpdb->posts.ID) WHERE comment_approved = '1' AND comment_type = '' AND post_password = '' ORDER BY comment_date_gmt DESC
LIMIT $src_count";
$comments = $wpdb->get_results($sql);
$output = $pre_HTML;
foreach ($comments as $comment) {
$output .= "<li><a href=\"" . get_permalink($comment->ID) . "#comment-" . $comment->comment_ID . "\" title=\"on " . $comment->post_title . "\">" . strip_tags($comment->com_excerpt) ."...</a></li>";
}
$output .= $post_HTML;
echo $output;
}
?>

Then, to display the actual output, just use this code anywhere in your theme.

<?php recent_comments(); ?>

17.  Remove Curly Quotes from Your Posts

There are actually two different types of quotes that you can use.  There are the commonly used ones on your keyboard, and then there are the pretty looking ones that WordPress uses.

WordPress automatically replaces all of your quotes with curly quotes, and this can sometimes mess up code you have in your posts.  To avoid this, paste the following code in your functions.php file.

<?php remove_filter('the_content', 'wptexturize'); ?>

18. List Categories as a Dropdown

If you want to list the categories on your blog as a dropdown, use the following code anywhere within your theme files.

<?php wp_dropdown_categories( ); ?>

19. Display a Login/Logout Link

Blogs that allow user registration may find it helpful to display a logout/login link for use by themselves and their visitors.

<?php wp_loginout(); ?>

20. Display a Admin Panel/Register Link

Many theme developers just put a direct link to the WordPress admin panel if they want one.  Well, WordPress has a built-in function that will display as a register link and automatically change to a link to the admin panel when the user logs in.

<?php wp_register(); ?>

21. Display Ads on Old Posts

We already know how to disable commenting on older posts.  Well, it’s also plausible that you may want to insert advertisements on those posts.

Paste the following code into your functions.php file -

function is_old_post($post_id=null){
   $days = 30;
   global $wp_query;
   if(is_single() || is_page()) {
      if(!$post_id) {
         $post_id = $wp_query->post->ID;
      }
      $current_date = time();
      $offset = $days *60*60*24;
      $post_id = get_post($post_id);
      $post_date = mysql2date('U',$post_id->post_date);
      $cunning_math = $post_date + $offset;
      $test = $current_date - $cunning_math;
      if($test > 0){
         $return = true;
      }else{
         $return = false;
      }
   }else{
      $return = false;
   }
   return $return;
}

Then, place the following in your single.php file.

<?php if(is_old_post()){ ?>
INSERT AD CODE HERE
<?php } ?>

22. Display the Total Number of Posts

If you want to showoff how many posts you’ve made on your blog, you might want to try out this code. ( I think I’m at 5 right now :P )

<?php $numposts = $wpdb->get_var("SELECT count(*) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post'");
if (0 < $numposts)
     $numposts = number_format($numposts);
echo $numposts.' posts.';
?>

23. Display an Ad after the First Post

If you want to display an ad after the first post, place the following code right before the endwhile in the Loop of your WordPress theme (index.php).


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

Then, you’ll need to place the code for your ads in a file called “ad.php”

24.  Display Featured Posts

If you want to add featured posts functionality to your WordPress blog, you’ll first need to give each of your featured posts a category of “featured” or something similar.

Then place the following code in your theme files -


<?php query_posts('cat=2&showposts=5'); ?>  <ul>   <?php while (have_posts()) : the_post(); ?>   <li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>   <?php endwhile;?> </ul>

The number after “cat=” should be changed to fit the ID of your featured category.

25. Exclude a Certain Category From being Shown

If you don’t want a certain category to be shown, use the following code -

<?php query_posts('cat=-YOUR CATEGORY ID NUMBER'); ?>  <?php while (have_posts()) : the_post(); ?>   //the loop here <?php endwhile;?>

THAT’S ALL FOLKS

Well, I hope you all feel a bit smarter than you did prior to reading this.  Hopefully you’ll find these tips and tricks as useful as I have.  If you have any problems with one of them, you can always comment below.  Good luck!

For the record, this post consists of 1982 words.

Thank you for printing out this article. I'm glad you found the content on this site useful, and I hope you found everything you were looking for. For more awesome content like this, just visit http://net-cake.com, and contact me with any questions or concerns.

Share this post!

« »

Comments

  1. Tim January 31st, 20108:44 pm

    Really helpful post, I’m definitely using those. Hope you keep posting.

    ( Reply )
  2. Benje January 31st, 20108:56 pm

    Pretty useful, thanks.

    ( Reply )
  3. Paul D'Amora January 31st, 20108:58 pm

    Thanks for the comments guys!

    ( Reply )
  4. Kris February 1st, 20107:07 pm

    Well organized and very helpful. I’ll definitely be coming back to this post.

    ( Reply )
  5. Sean February 3rd, 20103:42 am

    Thanks, I was wondering how people got the allowed tags list into the comments section. I just added it to mine just then.

    Very helpful stuff, I’ll be sure to come back here.

    ( Reply )
  6. UGG Boots February 10th, 20101:21 pm

    I found this article useful in a paper I am writing at university. Hopefully, I get an A+ now!

    Thanks

    Bernice Franklin

    ( Reply )
  7. phpbb February 21st, 20106:08 pm

    Thanks! This helped a lot! I’ve seen several
    rather confusing websites lately, this cleared up some confusion I had.

    ( Reply )
  8. account money February 27th, 20104:25 pm

    After reading you site, Your site is very useful for me .I bookmarked your site!

    ( Reply )
  9. econgeevame March 5th, 20103:48 am

    i actually enjoy your own posting kind, very attractive,
    don’t quit as well as keep creating in all honesty , because it simply just good worth to follow it,
    excited to look into much more of your content pieces, have a good day :)

    ( Reply )
  10. free game downloads April 15th, 201011:50 am

    great share, great article, very usefull for me…thank

    you

    ( Reply )

Trackbacks/Pingbacks

  1. 25 Wordpress Tips and Tricks to Make Your Theme Awesome « Links
  2. Inactivity « Fynmark.org

Leave a Reply