.. Your Daily Design Dosis

10 Useful WordPress Hacks/Code Snippets

| 11 Comments

WordPress is the most used open source Content Management System (CMS) in our world, often used as a blog publishing application, powered by PHP and MySQL. It has many features including a plug-in architecture and a template system.

WordPress comes with standard functions and we can use plugins or code snippets to give our blog a different look or function(s). Personally I prefer code snippets and hacks more than using a plugin to get a feature up and running, this because a code snippet is pure, while a plugin comes from a 3rd party and could be filled with non-valide codes or bloated codes?

Today I want to share some more WordPress hacks and code snippets which I’ve found on many WordPress related blogs. But before I begin, a short word of warning ..

Note: These hacks worked at the time they were published, but as new versions of WordPress are released, some may no longer work.  Please backup your theme before attempting any hacks so you can restore things if something goes wrong.

Display Search Terms from Google users

Paste this anywhere outside the header to display all the search terms your visitors will have used to find your site.

<?php
$refer = $_SERVER["HTTP_REFERER"];

if (strpos($refer, "google")) {
<span style="white-space: pre;"> </span>$refer_string = parse_url($refer, PHP_URL_QUERY);
<span style="white-space: pre;"> </span>parse_str($refer_string, $vars);
<span style="white-space: pre;"> </span>$search_terms = $vars['q'];
<span style="white-space: pre;"> </span>echo 'Welcome Google visitor! You searched for the following terms to get here: ';
<span style="white-space: pre;"> </span>echo $search_terms;
};
?>

Source: WP Snippets

Custom Page Style

Page templates are great for differentiating different types of pages. You can use this snippet. Just drop it into a new PHP file and upload it. You’ll be able to access it by using the page template dropdown menu when creating a page.

/* Template name: Custom Page Name */
/* Describe the custom page here! */
get_header();
# The loop n' all! #
the_sidebar();
get_footer();

Source: Lava 360

Track Post View Amount by Using Post Meta

For a simple way to keep track of the number of post views, paste this snippet into the functions.php, and then follow steps 1 and 2.

function getPostViews($postID){
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
return "0 View";
}
return $count.' Views';
}
function setPostViews($postID) {
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
$count = 0;
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
}else{
$count++;
update_post_meta($postID, $count_key, $count);
}
}

Step 1: Paste the code below within the single.php within the loop:

<?php setPostViews(get_the_ID()); ?>

Step 2: Paste the snippet below anywhere within the template where you would like to display the number of views:

<?php echo getPostViews(get_the_ID()); ?>

Source: wpsnipp

Breadcrumbs Without a Plugin

Breadcrumbs can be a useful navigation technique that offers link to the previous page the user navigated through to arrive at the current post/page. There are plugins you could use, but the code snippet below could be an easier solution.

Paste this code into your functions.php file.

function the_breadcrumb() {
echo '
<ul id="crumbs">';
if (!is_home()) {
echo '
	<li><a href="'; echo get_option('home'); echo '">';
echo 'Home';
echo "</a></li>
";
if (is_category() || is_single()) {
echo '
	<li>';
the_category('</li>
	<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>
';
}

Then paste the calling code below, wherever you would like the breadcrumbs to appear (typically above the title tag).

<?php the_breadcrumb(); ? >

Source: wp-snippets

wordpress-code-snippets

Display an External RSS Feed

This snippet will fetch the latest entries of any specified feed url.

<?php include_once(ABSPATH.WPINC.'/rss.php');
wp_rss('http://wpforums.com/external.php?type=RSS2', 5); ?>

This code takes the rss.php file that is built into WordPress (used for widgets). It is set to display the most recent 5 posts from the RSS feed ‘http://example.com/external.php?type=RSS2′.

Source: wphacks

Custom Excerpts

Sometimes you may need to limit how many words are in the excerpt, with this snippet you can create your own custom excerpt (my_excerpts) replacing the original.

Paste this code in functions.php:

<?php add_filter('the_excerpt', 'my_excerpts');
function my_excerpts($content = false) {
global $post;
$mycontent = $post->post_excerpt;
$mycontent = $post->post_content;
$mycontent = strip_shortcodes($mycontent);
$mycontent = str_replace(']]>', ']]>', $mycontent);
$mycontent = strip_tags($mycontent);
$excerpt_length = 55;
$words = explode(' ', $mycontent, $excerpt_length + 1);
if(count($words) > $excerpt_length) :
array_pop($words);
array_push($words, '...');
$mycontent = implode(' ', $words);
endif;
$mycontent = '<p>' . $mycontent . '</p>';
// Make sure to return the content
return $mycontent;
}
?>

Secondly, paste this code within the Loop:

<?php echo my_excerpts(); ?>

Source: wptricks

Redirect to Single Post If just one Post in Category/Tag

If there is only one post within a category or tag, this little snippet will jump the reader directly to the post page.

Paste this code into your themes functions.php file:

function stf_redirect_to_post(){
global $wp_query;
// If there is one post on archive page
if( is_archive() && $wp_query->post_count == 1 ){
// Setup post data
the_post();
// Get permalink
$post_url = get_permalink();
// Redirect to post page
wp_redirect( $post_url );
}
} add_action('template_redirect', 'stf_redirect_to_post');

Source: shailan

Add Content to the End of Each RSS Post

Adding some extra content that is only viewable by your RSS subscribers couldn’t be easier with this snippet.
Paste this code into the functions.php:

function feedFilter($query) {
if ($query->is_feed) {
add_filter('the_content','feedContentFilter');
}
return $query;
}
add_filter('pre_get_posts','feedFilter');
function feedContentFilter($content) {
$content .= '<p>Extra RSS content goes here... </p>';
return $content;
}

Source: wptricks

One size for your Post Thumbnails

If you enable post thumbnails for your theme, you will find that you may not like the default size (150×150 px). If you want all of your post thumbnail images to be the same size throughout your theme, then you can set it in functions.php:

set_post_thumbnail_size( 100, 100 ); // 100 pixels wide by 100 pixels tall, box resize mode

or:

set_post_thumbnail_size( 100, 100, true ); // 100 pixels wide by 100 pixels tall, hard crop mode

Source: WPMU

How to Disable Right-Clicking on Your WordPress Blog

If you have a lot of copyrighted images or you don’t want people stealing parts of your design, here’s a quick way to disable right-clicking within WordPress. There are plugins that will do this for you, but I think this is easier than installing a plugin. Open your header.php file and add this jQuery snippet right before the closing </head> tag:

<script type="text/javascript">
$(document).ready(function(){
    $(document).bind("contextmenu",function(e){
        return false;
    });
});
</script>

Source: WPMU

- § -

I hope you’ve enjoyed this resourceful article. If you’ve liked this article, please retweet, and share it with your friends on Facebook. If you think I’ve missed a very special or great hack or snippet, please let me know by filling in a comment … cheers!

 

Author: Jan Rajtoral

Jan Rajtoral AKA Gonzo the Great is the Founder of and Designer at gonzodesign, providing design services across the full spectrum of Brand Identity, Graphic Design, Print and Advertising Design & Website Design.

11 comments

on this article: “10 Useful WordPress Hacks/Code Snippets”
  1. except the last example should be moved into a post called “the most useless code snippets”. Everybody knows how to get around this, plus it creates usability issues. Watermark your images if youre worried people will steal your shit or dont put it online. Disabling right click has never been and will never be the solution to this

    • Hi Adam,

      thanks for your comment, and yes, I do partly agree with you. BTW a good tip to ‘watermark’ your image if you’re afraid somebody will steal your graphic or picture, thanks for that. But I included this snippet because I know one client wanted (insisted) on this feature ..

      Thanks for your time to comment, hope you liked the other 9 snippets? Enjoy your day, Cheers & Ciao ..

  2. Hey thanks for posting my snippet glad you like the site.

    • Hi Kevin,

      you’re welcome, and yep, love your site! Keep up the good work and maybe I’ll post more of your snippets ;-P
      Thanks for dropping by, Cheers & Ciao ..

  3. Thanks Gonzo for the help. I’m looking at reducing the number of plugins on my blog and having code snippets will help a lot.

    • Hi Gabi,

      Plugins and widgets also make your blog load slower, and we all know how important load time is for Google ;-P
      Thanks for your comment and good luck with coding! Cheers & Ciao ..

      BTW: love your blog, I have made a Tumblr blog myself and will be offering it for free soon (http://gonzoblog-theme.tumblr.com/)

  4. You can be the first to comment!
    +1

  5. Rad! I just added a few to my blog. I’m playing around with your custom excerpts function, that may just solve a few problems I’m having. Thanks for the snippets!

    • Hi Patrick,

      How are you doing? Love your new blurbherd.com blog and thanks for putting this article into the ‘herd’, much appreciated!

      I’m also glad I helped you somehow, I myself I love the custom excerpt code because it gives you the possibility to use more versions than only the default excerpt-size (meaning: different numbers of words per excerpt). For instance in the indexpage, where you don’t have much space for an excerpt containing 55 words, you can make a 2nd version for 20-25 words – eeehr, .. if you catch my drift here ;-P

      I wish you success with your new blog, and check out some other articles here (see ‘Related Post’) for more useful WP hacks for your blog .. Keep those tweets coming and smell ya later .., Cheers & Ciao Amigo!

top