free website hit counter
RSS Feed     Twitter     Facebook
Room 09 Shop
Read Detail
Live Demo
Buy Now
Simplicity eCommerce
Read Detail
Live Demo
Buy Now
Bazar Shop
Read Detail
Live Demo
Buy Now
The Retailer
Read Detail
Live Demo
Buy Now
Phomedia E-Commerce
Read Detail
Live Demo
Buy Now

10 Useful Coding Techniques of WordPress

Font size:
  • Sharebar

Since last year, the WordPress themes market has grown incredibly. The reason? Great designs, of course, but also a lot of amazing new functionality. Top WordPress developers are always looking to get the most out of WordPress and use all of their knowledge to find ways to make their favorite blogging engine even more powerful.

In this article, we have compiled 10 useful WordPress code snippets, hacks and tips to help you create a WordPress theme that stands out from the crowd.

You may be interested in the following related posts:

(Smashing’s note: If you enjoy reading our articles, you’ll love the Smashing eBook Library. Get immediate access to all Smashing eBooks with 70% discount and vote on the topics you’d like to learn more about. We’ll prepare eBooks that fit your needs best! Subscribe now!)

1. Style Posts Individually

Screenshot

The problem.
Your blog has a lot of posts, but the posts aren’t all of the same type. To give special styling to one or more of your posts, you can take advantage of both the post_class() function and the post ID.

The solution.
To apply this trick, just open your single.php file, find the loop and replace it with the following:

1 <?php if (have_posts()) : ?>
2 <?php while (have_posts()) : the_post(); ?>
3 <div <?php post_class() ?> id="post-<?php the_ID(); ?>">
4 <h3><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h3>
5 <?php the_content(); ?>
6 </div>
7 <?php endwhile; else: ?>
8 <?php _e('Sorry, no posts matched your criteria.'); ?>
9 <?php endif; ?>

Code explanation.
The important part is mostly in line 3. Here, we have added the PHP post_class() function. Introduced in WordPress 2.8, this function adds CSS classes to the post. For example, it can add:

  • .hentry
  • .sticky
  • .category-tutorials
  • .tag-wordpress

With these CSS classes now added, you can now give a custom style to all posts that have the sticky tag or those that belong to the tutorials category.

The other important piece of this code is id="post-<?php the_ID(); ?>". By displaying the ID of the post here, we’re able to style a particular post. As an example:

1 #post-876{
2     background:#ccc;
3 }

Source:

2. Display Related Posts… With Thumbnails!

Screenshot

The problem.
After they have read your latest post, what do your readers do? That’s easy: most of them simply leave. A great way to keep them interested is to display a list of related posts. Many plug-ins can do that, but for those who like to know how things works, here is some nice code to get related posts and their thumbnails.

The solution.
Simply paste this code after the the_content() function in your single.php file:

01 <?php
02 $original_post = $post;
03 $tags = wp_get_post_tags($post->ID);
04 if ($tags) {
05   echo '<h2>Related Posts</h2>';
06   $first_tag = $tags[0]->term_id;
07   $args=array(
08     'tag__in' => array($first_tag),
09     'post__not_in' => array($post->ID),
10     'showposts'=>4,
11     'caller_get_posts'=>1
12    );
13   $my_query = new WP_Query($args);
14   if( $my_query->have_posts() ) {
15     echo "<ul>";
16     while ($my_query->have_posts()) : $my_query->the_post(); ?>
17       <li><img src="<?php bloginfo('template_directory'); ?>/timthumb/timthumb.php?src=<?php echo get_post_meta($post->ID, "post-img", true); ?>&h=40&w=40&zc=1" alt="" /><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
18     <?php endwhile;
19     echo "</ul>";
20   }
21 }
22 $post = $original_post;
23 wp_reset_query();
24 ?>

Code explanation.
First, this code makes use of TimbThumb, a PHP image-resizing script. We have used it to automatically resize images to 40 by 40 pixels.

Once this code is pasted in your theme, it uses the first tag of the post to fetch related posts. In this example, four related posts are displayed. You can change this number on line 10.

Also, notice that I have cloned the $post variable at the beginning of the script and restored it at the end. This prevents problems that may occur with the loop, such as comments being assigned to the wrong post.

Source:

3. Alternate Post Styling On Your Home Page

Screenshot

The problem.
Many new WordPress themes have an amazing way of displaying posts on the home page. For example, we can display the first three posts bigger than the rest, with images and extended text, with the remaining posts shown more simply.

I have seen many themes in which developers use two distinct loops to achieve this, which isn’t necessary and can cause further problems. Let’s use a much simpler method.

The solution.
Here is a custom loop that displays the first three posts different than the rest. You can replace the existing loop in your index.php file with this code.

01 <?php
02 $postnum = 0;
03 while (have_posts()) : the_post(); ?>
04
05 <?php if ($postnum <= 3){ ?>
06 <div <?php post_class() ?> id="post-<?php the_ID(); ?>">
07   <div class="date"><span><?php the_time('M j') ?></span></div>
08     <h2>(<?php echo $postnum;?>)<a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
09     <div class="post-image" style="text-align:center;">
10         <a href="<?php the_permalink() ?>"><img src="<?php bloginfo('template_directory' ); ?>/timthumb.php?src=<?php  echo catch_that_image(); ?>&amp;w=500&amp;h=200&amp;zc=1" alt="<?php the_title(); ?>" /></a>
11     </div>
12     <p><?php the_content('Read the rest of this entry &raquo;'); ?></p>
13     <p class="more"><a href="#">Read More</a></p>
14   </div>
15 </div>
16
17 <?php } else {
18 <div <?php post_class( 'single ' . $end ); ?> id="post-<?php the_ID(); ?>">
19     <div class="post-content">
20         <h3><a href="<?php the_permalink() ?>">(<?php echo $postnum; ?>)<?php the_title(); ?></a> <?php edit_post_link('_', '', ''); ?></h3>
21         <p><?php the_excerpt( '' ); ?></p>
22         <p class="more"><a href="#">Read More ?</a></p>
23     </div>
24 </div><!-- End post -->
25
26 <?php }
27     endwhile;
28     ?>

Code explanation.
Nothing hard here! We just created a PHP variable, named $postnum, which is invoked at the end of the loop. If $postnum is less than or equal to 3, the post is displayed in full. Otherwise, it is displayed in its more compact form.

4. Using Multiple Loops

Screenshot

The problem.
When coding complex WordPress pages with more than one loop, it can happen that one of the loops doesn’t behave as expected: for example, unwanted offset, repeated posts, etc. Happily, with a bit of knowledge and a very useful function, we can avoid this.

The solution.
The following example features two distinct loops. Notice the rewind_posts() function on line 8. This example can be used on any WordPress file as is: index.php, single.php, etc.

01 // First loop (get the last 3 posts in the "featured" category)
02 <?php query_posts('category_name=featured&showposts=3'); ?>
03 <?php while (have_posts()) : the_post(); ?>
04   <!-- Do stuff... -->
05 <?php endwhile;?>
06
07 //loop reset
08 <?php rewind_posts(); ?>
09
10 //Second loop (Get all posts)
11 <?php while (have_posts()) : the_post(); ?>
12   <!-- Do stuff... -->
13 <?php endwhile; ?>

Code explanation.
This piece of code doesn’t use any hacks; rewind_posts() is a standard WordPress function.

The purpose of rewind_posts() is to “clear” a loop that has been previously used (like the first loop in our example above), allowing you to use a second loop that isn’t affected by the first loop’s results.

Source:

5. Overwrite Post Titles Easily

Screenshot

The problem.
the_title() is a basic but very useful WordPress function: it displays the post or page’s title. No more, no less. But hey, have you ever wished you were able to display the full title in your listing of posts and a custom title on the actual post’s page? If so, find out how right here.

The solution.
In your single.php file, find the call to the the_title() function and replace it with the following code:

1 <?php $title = get_post_meta($post->ID, "custom-title", true);
2 if ($title != "") {
3     echo "<h1>".$title."</h1>";
4 } else { ?>
5     <h1><?php the_title(); ?></h1>
6 <?php } ?>

Once that’s done, you can rewrite the post’s title by creating a field named custom-title. Its value will be your custom title for this post.

Code explanation.
When this code loads, it retrieves the meta field named custom-title. If this meta field exists and isn’t blank, it is displayed as the post’s title. Otherwise, the the_title() function is called, and the post’s regular title is displayed.

Source:

6. Add Multiple Sidebars

Screenshot

The problem.
Sidebars are great because they allow you to display a lot of useful info, such as related posts, author info, a blog roll, 125×125-pixel ad spaces and so on. But sidebars can quickly become very busy, and readers may be hard-pressed to find what they’re looking for. So, what about having different sidebars available and displaying the most appropriate one for the post?

The solution.
To apply this hack, duplicate your sidebar.php file and fill it with whatever information you would like to appear. Save the file as sidebar-whatever.php.

Once that’s done, open your single.php* file and find the call to the get_sidebar() function:

1 <?php get_sidebar(); ?>

Replace it with:

1 <?php $sidebar = get_post_meta($post->ID, "sidebar", true);
2 get_sidebar($sidebar);
3 ?>

Now when you write a post, create a custom field named sidebar. Set its value as the name of the sidebar that you want to include. For example, if its value is right, WordPress will automatically include sidebar-right.php as a sidebar.

If no custom sidebar field is found, WordPress automatically includes the default sidebar.

*The same can be done with page.php.

Code explanation.
This trick is quite simple. The first thing we did was look for a custom field named sidebar and get its value as a variable. Then, the variable is used as a parameter for the WordPress function get_sidebar(), which allows us to specify a particular file to use as a sidebar.

Source:

7. Display Content Only To Registered Users

Screenshot

The problem.
As you probably know, WordPress lets you decide whether to allow readers to create accounts and sign in to your blog. If you want to increase your blog’s registered readers or would just like to reward existing readers, why not keep some content private, just for them?

The solution.
To achieve this hack, we’ll use a shortcode. The first step is to create it. Open your functions.php file and paste the following code:

1 function member_check_shortcode($atts, $content = null) {
2   if (is_user_logged_in() && !is_null($content) && !is_feed()) {
3     return $content;
4   } else {
5     return 'Sorry, this part is only available to our members. Click here to become a member!';
6 }
7
8 add_shortcode('member', 'member_check_shortcode');

Once that’s done, you can add the following to your posts to create a section or text (or any other content) that will be displayed only to registered users:

1 [member]
2 This text will be displayed only to registered users.
3 [/member]

That’s it. Registered users will see the text contained in the shortcode, while unregistered users will see a message asking them to register.

Code explanation.
The first thing we’ve done is create a function named member_check_shortcode, which checks whether the current user is logged in. If they are, then the text contained in the [member] shortcode is displayed. Otherwise, the message on line 5 is shown.

If you’d like to know more about WordPress shortcodes, you should definitely have a look at our Mastering WordPress Shortcodes post.

Source:

8. Display Your Most Popular Content In The Sidebar

Screenshot

The problem.
If you want to feature your best content and help readers discover more articles from your blog, you might want to display a list of your most popular posts, based on the number of comments they’ve received, in your sidebar.

The solution.
This code is really easy to implement. Just paste it wherever you’d like your popular posts to appear. To get more or less than five posts, just change the value of the SQL limit clause on line 3.

01 <h2>Popular Posts</h2>
02 <ul>
03 <?php $result = $wpdb->get_results("SELECT comment_count,ID,post_title FROM $wpdb->posts ORDER BY comment_count DESC LIMIT 0 , 5");
04 foreach ($result as $post) {
05 setup_postdata($post);
06 $postid = $post->ID;
07 $title = $post->post_title;
08 $commentcount = $post->comment_count;
09 if ($commentcount != 0) { ?>
10 <li><a href="<?php echo get_permalink($postid); ?>" title="<?php echo $title ?>">
11
12 <?php echo $title ?></a> {<?php echo $commentcount ?>}</li>
13 <?php } } ?>
14 </ul>

Code explanation.
In this code, we use the $wpdb object to send a custom SQL query to the WordPress database. Then we verify that the results aren’t empty (i.e. that no posts are without comments), and finally we display the list of posts.

Sources

9. Create A Drop-Down Menu For Easy Tag Navigation

Screenshot

The problem.
Tags are cool because they allow you to categorize content using precise terms. But displaying tag clouds is a problem: they are ugly, not easy to use and can be extremely big.

So, what’s the solution? Simply create a drop-down menu for your tags. That way, they don’t get in the way, but people still have easy access to them.

The solution.
To create our drop-down menu of tags, we first have to paste the two functions below into the functions.php file of our WordPress theme:

01 <?php
02 function dropdown_tag_cloud( $args = '' ) {
03     $defaults = array(
04         'smallest' => 8, 'largest' => 22, 'unit' => 'pt', 'number' => 45,
05         'format' => 'flat', 'orderby' => 'name', 'order' => 'ASC',
06         'exclude' => '', 'include' => ''
07     );
08     $args = wp_parse_args( $args, $defaults );
09
10     $tags = get_tags( array_merge($args, array('orderby' => 'count', 'order' => 'DESC')) ); // Always query top tags
11
12     if ( empty($tags) )
13         return;
14
15     $return = dropdown_generate_tag_cloud( $tags, $args ); // Here's where those top tags get sorted according to $args
16     if ( is_wp_error( $return ) )
17         return false;
18     else
19         echo apply_filters( 'dropdown_tag_cloud', $return, $args );
20 }
21
22 function dropdown_generate_tag_cloud( $tags, $args = '' ) {
23     global $wp_rewrite;
24     $defaults = array(
25         'smallest' => 8, 'largest' => 22, 'unit' => 'pt', 'number' => 45,
26         'format' => 'flat', 'orderby' => 'name', 'order' => 'ASC'
27     );
28     $args = wp_parse_args( $args, $defaults );
29     extract($args);
30
31     if ( !$tags )
32         return;
33     $counts = $tag_links = array();
34     foreach ( (array) $tags as $tag ) {
35         $counts[$tag->name] = $tag->count;
36         $tag_links[$tag->name] = get_tag_link( $tag->term_id );
37         if ( is_wp_error( $tag_links[$tag->name] ) )
38             return $tag_links[$tag->name];
39         $tag_ids[$tag->name] = $tag->term_id;
40     }
41
42     $min_count = min($counts);
43     $spread = max($counts) - $min_count;
44     if ( $spread <= 0 )
45         $spread = 1;
46     $font_spread = $largest - $smallest;
47     if ( $font_spread <= 0 )
48         $font_spread = 1;
49     $font_step = $font_spread / $spread;
50
51     // SQL cannot save you; this is a second (potentially different) sort on a subset of data.
52     if ( 'name' == $orderby )
53         uksort($counts, 'strnatcasecmp');
54     else
55         asort($counts);
56
57     if ( 'DESC' == $order )
58         $counts = array_reverse( $counts, true );
59
60     $a = array();
61
62     $rel = ( is_object($wp_rewrite) && $wp_rewrite->using_permalinks() ) ? ' rel="tag"' : '';
63
64     foreach ( $counts as $tag => $count ) {
65         $tag_id = $tag_ids[$tag];
66         $tag_link = clean_url($tag_links[$tag]);
67         $tag = str_replace(' ', '&nbsp;', wp_specialchars( $tag ));
68         $a[] = "\t<option value='$tag_link'>$tag ($count)</option>";
69     }
70
71         switch ( $format ) :
72     case 'array' :
73         $return =& $a;
74         break;
75     case 'list' :
76         $return = "<ul class='wp-tag-cloud'>\n\t<li>";
77         $return .= join("</li>\n\t<li>", $a);
78         $return .= "</li>\n</ul>\n";
79         break;
80     default :
81         $return = join("\n", $a);
82         break;
83     endswitch;
84
85     return apply_filters( 'dropdown_generate_tag_cloud', $return, $tags, $args );
86 }
87 ?>

Once you’ve pasted this function in your functions.php file, you can use it to create your drop-down menu of tags. Just open the file where you want the list to be displayed and paste the following code:

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

Code explanation.
To achieve this hack, we take the wp_tag_cloud() WordPress function and rewrite it to make it display tags in an HTML “Select” element.

Then, we just call the newly created dropdown_tag_cloud() in our theme to display the drop-down menu items.

Source:

10. Auto-Resize Images Using TimThumb And WordPress Shortcodes

Screenshot

The problem.
A good blog post needs images, whether screenshots or simple eye-candy. Readers always prefer articles with nice pictures to plain boring text.

But images can be a pain to deal with, especially because of their various sizes. So how about we create a WordPress shortcode that uses Timthumb to automatically resize images?

The solution.
The first thing to do is create the shortcode. Paste the following code in your functions.php file:

1 function imageresizer( $atts, $content = null ) {
2     return '<img src="http://media.smashingmagazine.com/wp-content/uploads/2009/10//timthumb/timthumb.php?src='.$content.'&w=590" alt="" />';
3 }
4
5 add_shortcode('img', 'imageresizer');

Now, you can use the following syntax to add an automatically resized image to your blog post:

1 [img]http://www.yoursite.com/yourimage.jpg[/img]

Code explanation.
You have probably already noticed how cool WordPress shortcodes are and how they make your blogging life easier. This code simply creates a shortcode that takes a single parameter: the image’s URL. Please notice that it’s not a good idea to resize large images this way as it unnecessarily increases the server load – in such cases it’s better to create and upload smaller images instead.

TimThumb resizes the image to 590 pixels wide, as specified on line 2 (w=590). Of course, you can change this value or add a height parameter (e.g. h=60).

Source:

Related posts

You may be interested in the following related posts:

About the Author

This guest post was written by Jean-Baptiste Jung, a 27-year-old WordPress expert from the French-speaking part of Belgium. He blogs about WordPress at WpRecipes, about practical Web development tips at Cats Who Code and about blogging at Cats Who Blog. You can stay in touch with Jean by following him on Twitter.

Share with: Twitter Delicious Facebook Digg Stumbleupon Wordpress Googlebuzz Myspace Gmail Newsvine Favorites More
You can leave a response, or trackback from your own site.
Some More Popular News

Leave a Reply

 

Recent Search

TheTechjournal.com
Copyright© 2014 WordPress Planet | All Right Reserved.