Handy WordPress Code Snippets

Handy WordPress Code Snippets

Posted on 21. Sep, 2009 by Alex Denning in Quick Tips

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>

Get your highest score for cisco certification with help of ccvp online training and ccda practice tests.

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 WPShout – 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 WordPress 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 follow me on Twitter or subscribe by RSS?!

Related posts:

  1. Really Easy Custom Post Backgrounds For WordPress

Tags:

Follow on Twitter! Subscribe!
Alex's Gravatar

Alex Denning is the founder of WPShout. A WordPress developer from London, Alex co-founded WPShift at the start of 2010 where he sells awesome WordPress themes.

You can find Alex on Twitter and at AlexDenning.com.

17 Responses to “Handy WordPress Code Snippets”

  1. Jenny

    21. Sep, 2009

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

    Reply to this comment
  2. Abhishek

    22. Sep, 2009

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

    Reply to this comment
  3. Matt Wiebe

    22. Sep, 2009

    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 =-.

    Reply to this comment
    • Alex Denning

      22. Sep, 2009

      Fair point. In my defence, this was an article I wrote a fair while ago and when this was published I was away so I didn’t get a chance to check it.

      Indeed, body_class is something new, along with post_class – great article about that I saw the other day – http://epicalex.com/guest-post-on-pbd/

      Reply to this comment
  4. Karar

    23. Sep, 2009

    Very useful & nice article !
    Thank you so much

    Karar

    Reply to this comment
  5. Harsh Agrawal

    26. Sep, 2009

    Hey very useful and easy to implement

    Reply to this comment
  6. Boomer Sassmann

    29. Sep, 2009

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

    Reply to this comment
  7. George Serradinho

    30. Sep, 2009

    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 =-.

    Reply to this comment
  8. Ashfame

    02. Oct, 2009

    Reply to this comment
  9. Comment Name Violation

    20. Oct, 2009

    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!

    Reply to this comment

Trackbacks/Pingbacks

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

  2. [...] 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 [...]

  3. [...] 10 snippets WordPress pour coder plus vite [...]

  4. [...] – 10 Really Useful WordPress Code Snippets [...]

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

Leave a Reply

Please use your real name when commenting. Wrap code in <code> tags and make sure HTML is encoded. You can use regular HTML like <a href="... etc.

Get yours questions answered quicker

If you're using this post for paid work and have a question of any complexity then please ask at WPQuestions where you'll get a prompt response.