Building your own wordpress themes will open your eyes to a lot of things, mainly the fact that you’ll be retyping a lot of code over and over and over again. So in this post I am going to show you ten wordpress code hacks that you can add to your arsenal that will not only save you a lot of time, but they will also set your themes apart from others who don’t come pre built with these types of features.
Adding A Post Loop Anywhere In Your Theme ↓
Putting the code below anywhere in your themes files (sidebar.php, footer.php, header.php, ect) will pull the 5 most recent posts from a category named “Featured“. You can change the showposts=5 count to whatever you’d like and also change the category name. This is especially useful if you’re building a custom home page and want to show recent posts from different categories on your blog.
[html]
< ?php $my_query = new WP_Query(‘category_name=Featured&showposts=5’);
while ($my_query->have_posts()) : $my_query->the_post();
$do_not_duplicate = $post->ID; ?>
<!– POST CODES HERE –>
< ?php endwhile; ?>
[/html]
Showing Related Posts Without A Plugin (based on related tags) ↓
[html]
< ?php
$tags = wp_get_post_tags($post->ID);
if ($tags) {
$tag_ids = array();
foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;
$args=array(
‘tag__in’ => $tag_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>
‘;
}
}
?></ul>
[/html]
Source: Bin-Blog
Display Author Information For Posts ↓
By using the codes below in your single.php file, you will pull the information from the post author’s profile on your blog and show a bit about them. This is especially useful if you’ve got a lot of authors on your blog.
[html]
<div id="author-info">
<div id="author-image">
<a href="<?php the_author_meta(‘user_url’); ?>">< ?php echo get_avatar( get_the_author_meta(‘user_email’), ’80’, ” ); ?></a></div>
<div id="author-bio">
<h4>Written by < ?php the_author_link(); ?></h4>
< ?php the_author_meta(‘description’); ?>
</div>
</div>
<!–Author Info–>
[/html]
Source: Line 25
Showing Popular Posts In Your Sidebar ↓
Placing these codes in your sidebar.php file will show your sites most popular posts based on the comment count for the posts.
[html]
<h2>Popular Posts</h2>
<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>
[/html]
Source: Smashing Magazine
Displaying Ads In Your RSS Feed ↓
This code will insert advertisements into your rss feeds which can help link back to your site if you see a lot of content theives hijacking your content or if you’d just like to have another form of advertising built in (google ads, ect). Paste this code into your themes functions.php file and you’re good to go.
[html]
< ?php
function insertAds($content) {
$content = $content.’Originally found at an <a href="http://www.spyrestudios.com">Awesome Design Blog’;
return $content;
}
add_filter(‘the_excerpt_rss’, ‘insertAds’);
add_filter(‘the_content_rss’, ‘insertAds’);
?>
[/html]
A Login Form That Returns The Visitor To The Page They Logged In From ↓
If you like having a login form on your site but get upset that the login form doesn’t return the person to the page they were currently viewing, this is the perfect snippet of code for you to have in your hack bag.
[html]
< ?php if(!is_user_logged_in()) { ?>
<form action="<?php echo wp_login_url(get_permalink()); ?>" method="post">
<label for="log"><input type="text" name="log" id="log" value="<?php echo wp_specialchars(stripslashes($user_login), 1) ?/>" size="22" /> User</label>
<label for="pwd"><input type="password" name="pwd" id="pwd" size="22" /> Password</label>
<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>
</form>
< ?php } ?>
[/html]
Adding Breadcrumbs To Your Theme Without A Plugin ↓
Breadcrumbs are a great way to allow visitors know where they currently are in your site and also give them options to easily find more posts from the category they’re in, ect. Adding breadcrumbs to your site is done in two steps – without a plugin. The code below needs to be added into your functions.php file for your theme.
[html]
function the_breadcrumb() {
echo ‘
<ul id="crumbs">’;
if (!is_home()) {
echo ‘
<li><a href="’;
echo get_option(‘home’);
echo ‘">’;
bloginfo(‘name’);
echo "</a></li>
";
if (is_category() || is_single()) {
echo ‘
<li>’;
the_category(‘title_li=’);
if (is_single()) {
echo "</li>
<li>";
the_title();
echo ‘</li>
‘;
}
} elseif (is_page()) {
echo ‘
<li>’;
echo the_title();
echo ‘</li>
‘;
}
}
elseif (is_tag()) {single_tag_title();}
elseif (is_day()) {echo"
<li>Archive for "; the_time(‘F jS, Y’); echo'</li>
‘;}
elseif (is_month()) {echo"
<li>Archive for "; the_time(‘F, Y’); echo'</li>
‘;}
elseif (is_year()) {echo"
<li>Archive for "; the_time(‘Y’); echo'</li>
‘;}
elseif (is_author()) {echo"
<li>Author Archive"; echo'</li>
‘;}
elseif (isset($_GET[‘paged’]) && !empty($_GET[‘paged’])) {echo "
<li>Blog Archives"; echo'</li>
‘;}
elseif (is_search()) {echo"
<li>Search Results"; echo'</li>
‘;}
echo ‘</ul>
‘;
}
[/html]
And the code below then needs to be added in your theme’s files where you’d like the breadcrumbs to show up (ie: single.php, page.php archive.php ect
[html]
< ?php the_breadcrumb(); ?>
[/html]
Insert Google Ads With WordPress Shortcodes ↓
The code below will give you the ability to insert adsense ads anywhere in your posts. This is great for people who like to add a 300×250 or 468×60 ad block in their posts but want the option to only add it into specific posts. First, we’ll add the code below into your theme’s functions.php file.
[html]
function showads() {
return ‘
<div class="adsensewrap"><script type="text/javascript"><!–
google_ad_client = "pub-XXXXXXXXXXXXXX";
google_ad_slot = "1234567890";
google_ad_width = 300;
google_ad_height = 250;
//–>
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
‘;
}
add_shortcode(‘adsense’, ‘showads’);
[/html]
Now, when you’re writing posts, you just add in the shortcode [adsense] and you’re all set. If you want to style the ad, I’ve wrapped the advertisement in a div class “adsensewrap“.
Source: Cats Who Code
Choose The Sidebar To Use On A Post By Post Basis ↓
Being able to choose which sidebar to use on a post by post basis would be a great idea for those of us who run websites that could utilize customized content in the sidebar based on category, ect. First, you’ll need to find the code below in your single.php file (and also in your index.php, page.php, etc…).
[html]
< ?php get_sidebar(); ?>
[/html]
And then replace it with this:
[html]
< ?php $sidebar = get_post_meta($post->ID, "sidebar", true);
get_sidebar($sidebar);
?>
[/html]
Now when you’ll write a post, create a custom field named sidebar. As a value, give it the name of the sidebar you want to include so if you’ve built three different sidebar files (sidebar-category.php, sidebar-full.php, sidebar-awesome.php) and wanted to show the sidebar-category.php file, you’d use the key “sidebar” and value “sidebar-category“.
Source: WP Recipes
Insert Social Media Submission Links In Your Theme Without A Plugin ↓
Most wordpress site owners these days use some form of social media plugin – but what if you could create your themes with the codes already built in? Well, it’s easier than you think. Add the below codes into your single.php file and you’re good to go with links for twitter, digg, delicious, reddit and stumbleupon.
[html]
<ul class="socialwrap">
<li><a href="http://digg.com/submit?phase=2&url=<?php the_permalink(); ?>&title=< ?php the_title(); ?>">Digg This Post</a></li>
<li><a href="http://twitter.com/home/?status=Reading <?php the_title(); ?> < ?php bloginfo(‘home’); ?>/?p=< ?php the_ID(); ?>">Tweet This Post</a></li>
<li><a href="http://www.stumbleupon.com/submit?url=<?php the_permalink(); ?>&title=< ?php the_title(); ?>">Stumble This Post</a></li>
<li><a href="http://delicious.com/post?url=<?php the_permalink(); ?>&title=< ?php the_title(); ?>">Save on Delicious</a></li>
<li><a href="http://www.reddit.com/submit?url=<?php the_permalink(); ?>&title=< ?php the_title(); ?>">Submit to Reddit</a></li>
</ul>
[/html]
Your Turn To Talk
I Hope you found this post useful! Any other tricks you have in your bag? Please take a minute to share them with the rest of us! :)
Pass VCP-410 exam with highest score using our cissp prep course and get certified in days. We also provide up to date dumps for mcp certification exam.
Thanks for the nice hacks collection! Though, you forgot the source of the “Google Adsense shortcode” : http://www.catswhoblog.com/how-to-display-adsense-ads-only-when-you-want-to
@Jean-Baptiste: Thanks for the heads up! I edited the post. Au plaisir :)
WOW. Very useful! Thank you! Even though you can find these hacks on other sites, it’s also good to have a summary like this.
Thanks for the quick hacks :)
I am thinking of learning more, rather than just installing plugins.
Thanks
Chris
@Jean-Baptiste – sorry about that. I thought I was missing a source in the list. Thanks Jon for adding it in.
Great list. For the first one, you might want to add a note about: wp_reset_query();
Very good list. I particularly like the custom sidebar. I never thought about it… so simple!
Thanks a lot. Very useful as right know I’m building my first wordpress based blog.
This post has just been added to my personal resource collection. Thanks for the collection of hacks…
Would anyone care to give a full explanation of why these functions.php hack are better than plug-ins?
Don’t misunderstand me, I use “hacks” and I am aware that they tend to use less resources and improve performance—but are these type of hacks a replacement for plug-ins? Are there examples of when a plug-in might be better? Just because it’s a hack placed in your functions.php file, does it mean it’s better?
I’d like a full explanation for best practices and advantages/disadvantages in regards to hacks vs plug-ins. Anyone care to give it a shot?
-B
@Jon Phillips : Thank you! Just tweeted the post :)
Potente post. Muy útil gracias desde Barcelona
If there is a plugin that can do most of these hacks why would you want to change the wordpress code? As I see it if anything changes with wordpress and breaks this hack you are screwed unless you remember exactly what you put in. Why not just use a plugin that you can turn off when problems arise?
Awesome examples. Retweeted and bookmarked and utilized! Thanks
Thanks for this collection. I use some of them on my blog. ;) Thanks!
Amazing hacks. I was looking for breadcrumb and I accidently discover it here.
Thanks for sharing.
An excellent list, and certainly good WordPress code…
but I have to question the use of the term “hack.”
Wouldn’t you agree that a “hack” is an exploitation of unintended functionality?
Everything you show here is straight from the WP documentation; all carefully made 100% available ahead of time by WP.
It may not be what is typically included in themes *by default* but it certainly is NOT outside the realm of what WP developers originally intended.
Great post! I’m always looking for WordPress hacks. Thanks! Just tweeted it as well.
Insert Social Media Submission Links In Your Theme Without A Plugin
I prefer to use the built in Links. I create a links category called Social then in the theme:
Now I can add/edit social bookmarks in the admin, without a plugin.
Quite a cool collection – just put the adsense one to work on a blug, albeit with a bit of tweaking for style. Thanks!
Nice collection here. Especially being able to have custom sidebars without having to install an extra plugin! Brilliant! Absolutely brilliant. Thanks Mike!
Thanks so much, this was a great article!
@bcarter – using these codes allows you to ensure that you know what’s being done, learn a bit of php and also ensure that if a plugin is not updated like it should be, you still have control over it all. I will try to do a post on WPguerrilla (or here if Jon wants me to) about the in depth response though :)
@jim – these codes aren’t changing core wordpress codes. they’re all done through your theme files, so if WP updates, 9 times out of 10, your codes will still work – and if they don’t, you just need to update the theme codes, NOT the wordpress core codes.
@ThatGuy – some of these items hack together 2-3 different pieces of wordpress code to get them to work properly, so yes, I believe they are hacks. They might be a part of the codex, but the majority of the time, they’re not used or utilized (not even in the default themes that wordpress comes with).
@Dave Jones – I never thought of doing that. thats a really good idea. Thanks for the tip.
Everyone else – Thank you for the comments. I am glad you enjoyed the post :) and remember, check out the sources for the tips as they’re all awesome sites with a ton of useful info too.
nice wp hacks! i have trying the tips that add author at the last of post. the function the_author_link() and others cannot be resolved. may be about my version of wordpress? my wp is 2.8.5
really good stuff, but just make sure you use <?php not < ?php
but thank for the hack, help me a lot in editing my theme.. :)
These are very useful tips, specially like bookmarking icon without plugin
Nice….This will be very useful. Thanks.
Interesting post, but why would you want to ‘hack’ something into your theme when you can use plug-ins for them? In the end you are more likely to create a maintenance nightmare for yourself.
As for the multiple loops you suggested: if you are going to do that make sure you use a plug-in like wp-cache in order to keep your site performing. Multiple loops means you double or triple the amount of calls you do to the database, which is a performance killer for high-performance sites.
Just my 2 cents.
Nice post, the more stuff you can do without a plugin, the better
Found a lot of these very useful. Especially that they are not just plugins. Thanks for all your work.
Hi I copy the breadcrumb code in my functions.php
I put the function in my header.php
there is nothing, neither the html tag ul in the source nor a breadcrumb,
so I put the function in single.php ==> the same
it doesn’t work
no error – simple nothing
did I miss something?
kindly regards
Monika
Love the article thanks a lot.
really great list, thanks :)
I was just looking for an “about the author” plugin a few minutes ago, gave up on finding a good one, and then started browsing some favorite tweets. I guess it’s my lucky day. Thanks man.
The RSS ad code doesn’t insert anything into my RSS feed. I must be missing something. Any idea what it might be? I inserted the code as you have it.
Nice article. The question of why do this instead of use plug-ins reminds me of the same talk about Frontpage. Coders thought it was bad to use because it did too much for you. The rest of us masses used it because it does so much for you.
Awesome!! thanks
WordPress for ever! thanks so much!
you should use nofollow to get better pagerank and PHP’s urlencode() function to encode titles so that stay valid
example for twitter:
<a rel="nofollow" href="http://twitter.com/home?status=” title=”Share this on Twitter”>Twitter
(great site btw!)
eh, the php tags in the example above got swallowed there :s
trying again with [ code ] [ /code ] .. hope this will work:
[code]<a rel="nofollow" href="http://twitter.com/home?status=” title=”Share this on Twitter”>Twitter[/code]
nice collection of hack :)
Great stuff! These will save me a couple of hours of coding every now and then :)
Added all of these to my WordPress scripts -library.
Hi, I put login hack and it works a bit strange :D have no idea, why :) from all pages it works ok, but when you login from the frontpage, it redirects you to the latest post single page :)
any ideas? :)
Cheers!
Roland
Regarding the custom sidebar, “Choose The Sidebar To Use On A Post By Post Basis”, you mention:
“First, you’ll need to find the code below in your sidebar.php file.
”
But that code is never found in the sidebar.php, in fact it’s the code that calls the sidebar.php. Now I’m not positive but if people put get_sidebar() into their sidebar.php files there’s probably going to be a looping issue.
I think what you mean to say is “find get_sidebar() in all of your page template files and your index.php, single.php, etc files and replace it with…”
A few beginners are probably pulling their hair out right now.
Once corrected, it’s an incredibly valuable and useful tip and I’m glad someone is posting it in such a compact and concise little snippet.
Great resource, thanks
Thanks for your nice post :)
Superb – all required wordpress code is at one place – these all are must for a wordpress blog to be considered. – Good one…..
Awesome! I’ll have to keep some of these in mind when I get a chance to work on a blog redesign.
The post theme loop is probably the best one; I’ve used it a few times when a client has requested two post pages, etc. Only problem with it is that it’s a bit temperamental when you’re also trying to put in a “numbered page” navigation.
Thank you for the WP “hacks”! I always like to use PHP code when I have simpler types of features instead of using plugins. I like your site and blog…easy to read and understand! Keep up the good work!
Just an addition to the first hack presented here:
After a custom wp_query, it’s always good practice to reset the query so you don’t have weird things happening in your theme.
This can be done simply by adding:
after the statement.
Thanks for the list, bookmarked!
Well, that didn’t work, so I’ve put it on Pastie as well: http://pastie.org/770075
Great post – I’ve bookmarked for future WP builds I do. Thanks!
i have some problem with the one of your list, show related post.
the problem is when i use that script in my page, it makes my comment number (have_comments function) won’t work and dissapear. so it just display “no comments” (actually i have 6 comments in there). how to fix this, and make all function work as usual..?
thx for your great list and the answer of this question.
THANK YOU! I was looking for this type of CSS codes for about an hour. I found here what just what I wanted
Great hacks and very useful too. Always worth having a several hacks in your arsenal for your blog, thanks.
nice collection, very usefull.. thanks
Great Post! It’s now postmarked and shared!
Thanks Again,
James
Great article! I just saw these at Target the other day and was impressed. Your review answered the questions I had about the seats – now I just need to scrape together the cash! Ouch!
Hi Mike,
I just put together a small function that allows you to create “test areas” in WordPress, so you can run code only when you are logged in as an admin user:
http://www.vidalquevedo.com/how-to-run-php-scripts-only-when-logged-in-as-admin/
Thanks, I hope you find this helpful and worthy of you list! =)
Vidal