Handy WordPress Code Snippets

There are certain snippets of WordPress code that you seem to end up using over and over again. In this post are ten great snippets that will make coding that bit easier.

1. List pages and categories in a drop down menu, excluding certain categories and limit the number of sub categories

This snippet will output categories in an unordered list, ordered by ID, categories limited to three levels deep and you can exclude certain categories by ID, separated with a comma.

<ul> <?php wp_list_categories('orderby=ID&order=ASC&depth=3&title_li=&exclude='); ?> </ul> 

Source – Codex For example, say I wanted to have a depth of 2 and exclude categories 12 and 13, I’d do so like this:

<ul> <?php wp_list_categories('orderby=ID&order=ASC&depth=2&title_li=&exclude=12,13'); ?> </ul>

If I’d prefer to list pages then simply change wp_list_categories to wp_list_pages.

2. Display the most popular posts, based on number of comments

A quick and easy plugin-less way to display a blog’s most popular posts is displayed below and can easily be integrated into any theme.

<ul> <?php $result = $wpdb->get_results("SELECT comment_count,ID,post_title FROM $wpdb->posts ORDER BY comment_count DESC LIMIT 0 , 5"); foreach ($result as $post) { setup_postdata($post); $postid = $post->ID; $title = $post->post_title; $commentcount = $post->comment_count; if ($commentcount != 0) { ?> <li><a href="<?php echo get_permalink($postid); ?>" title="<?php echo $title ?>"> <?php echo $title ?></a> {<?php echo $commentcount ?>}</li> <?php } } ?> </ul>

ProBlogDesign link

3. Display the latest sticky posts

A must for any ‘Magazine’ theme; sticky posts are becoming a replacement for the infamous and annoying ‘featured’ category. With the code below, you can display the latest sticky posts.

<?php /* Get all sticky posts */ $sticky = get_option( 'sticky_posts' ); /* Sort the stickies with the newest ones at the top */ rsort( $sticky ); /* Get the 2 newest stickies (change 2 for a different number) */ $sticky = array_slice( $sticky, 0, 2 ); /* Query sticky posts */ query_posts( array( 'post__in' => $sticky, 'caller_get_posts' => 1 ) ); ?>

Justin Tadlock link

4. Display meta information, including author, tags, number of comments and date published

Meta information is one of those things that every theme needs, but is just another little annoyance that needs sorting. The code below will display “Published by author on date, with x comments and tagged: tags.

Published by <?php the_author(); ?> on <?php the_time('n/d/y'); ?>, with <?php comments_number('no', 'one', '%'); ?> comments and tagged: <?php the_tags(); ?> 

5. Create a widgetised area with instructions on how to make use of it if no widgets are in use

I’m a big fan on making everything as easy as possible for the end user and one of the best ways to do this in WordPress is by widgetsing everything. However, the aforementioned end user might not quite realise how many widget areas you’ve popped into your theme – with the code below you can widgetise an area and then display a message instructing the end user how to make use of these widget areas if no widgets are in place.

<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('Widget Area') ) : ?> <h3>Widgetised area</h3> <p>This is a widgetised area. To fill it with 'stuff', use the “Widget Area” widget</p> <?php endif; ?>

You’ll also need the following code in your functions.php file:

<?php if ( function_exists('register_sidebar') ) register_sidebar(array( 'name' => 'Widget Area', 'before_widget' => 'you might want a <div class...> here', 'after_widget' => 'and a closing </div> here', 'before_title' => 'you might want a <h3> or <h4> here', 'after_title' => 'and </h3> or </h4> here', )); ?>

6.  Show breadcrumbs of Home / Post Category / Title

Breadcrumbs are great ways of showing your readers other posts in the same category, and you can display a breadcrumb of Home / Category / Title with the code below:

<?php bloginfo(‘home’); ?> / <?php the_category(); ?> / <?php the_title(); ?> 

7. Display (valid) social media links in a table

A great trick to add to your single.php file – a plugin-less way to have social media links at the bottom of posts. This trick requires you to have some social media icons, which you can find in abundance by Googling. Upload these icons to /your-theme/images/, naming them ‘socialmediasitename.png’ (ie delicious.png, reddit.png). The code below will probably look best after the content on your single posts. You’ll need to change the Twitter link to include your Twitter username.

<table border="0"> <tr> <td><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"><img src="<?php bloginfo('template_url'); ?>/images/delicious.png" alt="Share on Delicious" /></a></td> <td><a rel="nofollow" href="http://digg.com/submit?phase=2&amp;url=<?php the_permalink(); ?>" title="Submit this post to Digg"><img src="<?php bloginfo('template_url'); ?>/images/digg.png" alt="Share on Digg!" /></a></td> <td><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"><img src="<?php bloginfo('template_url'); ?>/images/reddit.png" alt="Share on Reddit!" /></a></td> <td><a rel="nofollow" href="http://feeds2.feedburner.com/nometech" title="Subscribe by RSS"><img src="<?php bloginfo('template_url'); ?>/images/rss.png" alt="Subscribe by RSS!" /></a></td> <td><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"><img src="<?php bloginfo('template_url'); ?>/images/stumbleupon.png" alt="Share on StumbleUpon!" /></a></td> <td><a rel="nofollow" href="http://twitter.com/home?status=<?php echo urlencode("RT @AlexDenning: "); ?><?php the_title(); ?> --> <?php the_permalink(); ?>" title="Share this article with your Twitter followers"><img src="<?php bloginfo('template_url'); ?>/images/twitter.png" alt="Share on Twitter!" /></a></td> </tr> </table>

8. Include jQuery the right way

This is a tip that has been doing the rounds recently but still very few people actually do it! The code below will include WordPress’ own copy of jQuery:

<?php wp_enqueue_script("jquery"); ?> Must be before wp_head. 

Source – Digging into WordPress

9. Give the <body> tag class of type of page, post/page ID and category

This is a great snippet that comes from the Thematic framework and needs to go into your functions.php file. What it does is add a class with the type of page, post/page ID, category etc etc. You’ll need the following in the functions.php file:

<?php // Generates semantic classes for BODY element function thematic_body_class( $print = true ) { global $wp_query, $current_user; // It's surely a WordPress blog, right? $c = array('wordpress'); // Applies the time- and date-based classes (below) to BODY element thematic_date_classes( time(), $c ); // Generic semantic classes for what type of content is displayed is_front_page() ? $c[] = 'home' : null; // For the front page, if set is_home() ? $c[] = 'blog' : null; // For the blog posts page, if set is_archive() ? $c[] = 'archive' : null; is_date() ? $c[] = 'date' : null; is_search() ? $c[] = 'search' : null; is_paged() ? $c[] = 'paged' : null; is_attachment() ? $c[] = 'attachment' : null; is_404() ? $c[] = 'four04' : null; // CSS does not allow a digit as first character // Special classes for BODY element when a singular post if ( is_singular() ) { $c[] = 'singular'; } else { $c[] = 'not-singular'; }

Download the whole snippet here And then replace

<body> 

with

<body class="<?php bodystyle(); ?>" > 

in the header file. With that done, you’re ready to rock.

10. Use custom fields to display images (and resize them with timthumb), with an alternate image if no images exist.

This is one of my favourite snippets that I use on a regular basis, even here on [wp] – it lets you set a custom field, ‘Image’ which then gets resized with timthumb (which you need to have uploaded to /yourtheme/scripts/) and displayed as a thumbnail on your archive pages/homepage. There’s an added twist though; if the custom field ‘Image’ isn’t found then an alternate image gets displayed. The code snippet below will do all of that:

<?php $postimageurl = get_post_meta($post->ID, 'Image', true); if ($postimageurl) { ?> <img src="<?php bloginfo(‘template_url’); ?> /scripts/timthumb.php?src=<?php echo get_post_meta($post->ID, "Image", true); ?>&h=250&w=250&zc=1" alt="<?php the_title(); ?>" /> <?php } else { ?> <img src="<?php bloginfo('template_url'); ?>/images/noimage.jpg" alt="No image available" /> <?php } ?>

Wrapping up

So there we have it. Ten code snippets that you might not have otherwise thought about using that you can easily insert into your theme. Not only are they easy to insert, but they’ll also take your [themes] to that lucrative next level. As always, any questions, points arising etc etc from this post, feel free to leave a comment and if you enjoyed this post, why not [t] or [s]?!


19 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
mark
November 16, 2010 2:24 am

I am going to use number 10 hopefully. Thanks for sharing this 🙂

Erin
August 25, 2010 11:21 am

Thank you. I was stuck on some code and this just sorted my issue!

Wordpress “Snippets” « WordPress Theme Mods
May 25, 2010 9:15 pm

[…] 1) 10 Really Useful WordPress Code Snippets | WPShout.com […]

Huge list of resources for Wordpress | Bastovanov Weblog
October 20, 2009 10:11 pm

[…] – 10 Really Useful WordPress Code Snippets […]

Links für Samstag, 26.09.2009 – 3 15 pm - Wordpresshosting
October 20, 2009 11:34 am

[…] 10 Really Useful WordPress Code Snippets […]

Comment Name Violation
October 20, 2009 2:00 am

Oh you Rock!! I was wondering how to do this with posts -> Most Comments ( # 2 ) thank you so much.. by the way, how do you make the code swing out on a mouse over? very cool!

10 snippets Wordpress pour coder + vite
October 9, 2009 8:44 am

[…] 10 snippets WordPress pour coder plus vite […]

Monthly Mother Lode of MacDaddy Links: September 2009 | bkmacdaddy designs
October 1, 2009 2:55 pm

[…] Tips and Tools to Combat Comment Spam in WordPress 10 Useful Usability Findings and Guidelines 10 Really Useful WordPress Code Snippets WordPress Web Optimization: 15 Tips And Plugins To Monitor, Speed Up And Optimize Your WordPress […]

George Serradinho
September 30, 2009 12:12 pm

Thanks for the help. I’m looking at reducing the number of plugins on my blog and having code snippets help a lot.
.-= George Serradinho´s last blog ..35 of the Most Popular WordPress Plugins =-.

Boomer Sassmann
September 29, 2009 6:12 am

Great article, nice bookmarking material for future reference on projects.

10 Really Useful WordPress Code Snippets | WPShout.com | My Web Development Bookmarks
September 27, 2009 6:10 pm

[…] See the article here: 10 Really Useful WordPress Code Snippets | WPShout.com […]

Harsh Agrawal
September 26, 2009 6:53 am

Hey very useful and easy to implement

Karar
September 23, 2009 12:39 am

Very useful & nice article !
Thank you so much

Karar

Matt Wiebe
September 22, 2009 3:00 pm

Some good snippets here, but some of them are outdated or problematic.

For example, #6 will only work for a top level category, ruling out pages and subcategories. Also, the home level on the trail isn’t linked to.

#9 is completely outdated as of WP 2.8, which introduced the body_class() function. Call it like this: >
.-= Matt Wiebe´s last blog ..That Delicious @font-face =-.

Abhishek
September 22, 2009 2:13 am

Nice snippets !! really ease of use for designer & Developers !
.-= Abhishek´s last blog ..Ek Sarfira =-.

Jenny
September 21, 2009 7:19 pm

Great article! Thanks!
.-= Jenny´s last blog ..Buchzitate aus “Der Schuß des Jägers”, Rafael Chirbes =-.