.. Your Daily Design Dosis

15+ Useful and Fresh WordPress Hacks / Snippets

| 4 Comments

Lately building some big(ger) WordPress Blogging/Corporate sites so to increase functionality I always look if there’s a little hack or code snippet available that can be tweaked for the purpose in mind. And that’s exactly why WordPress is the no.1 open source CMS for me, there’s so much information on the interwebs!

 

All these code snippets should work in WordPress 3.0+ (most of these I even tested ‘live’), but some of these hacks are so fresh, .. so, as always a word of warning for you guys ..

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.

In case you liked these wordpress hacks, make sure to check some more articles loaded with WordPress code snippets! Enough of the chitchat, let’s hit the road .. hope you’ll enjoy and use these!? Let me know in the Comment section, please?

 

 

Exclude a Category from Your WordPress Feed

If you’ve ever wanted to keep a certain category out of your RSS feed, there’s an easy way to do that. Just place the following code in your functions.php file. Simply insert the ID number from the category that you want to exclude in the spot where you see the “1″ in the example below. (Note: include the minus sign — e.g. -2, -5, etc.)

function excludecatfeed($query) {
               if(is_feed()) {
                              $query->set('cat','-1');
                              return $query;
               }
}
add_filter('pre_get_posts', 'excludecatfeed');

If you would like to exclude more than one category, then just include the other ID numbers beside the first like so:

$query->set('cat','-1, -5, -7');

 Source

 

Redirect users to a random post

What about giving a new life to your old posts by creating a page template that will redirect readers to a random post? Today, I’m going to show you how to easily create this kind of page. Create a new file and name it page-random.php. Paste the code below in it:

// set arguments for get_posts()
$args = array(
    'numberposts' => 1,
    'orderby' => 'rand'
);

// get a random post from the database
$my_random_post = get_posts ( $args );

// process the database request through a foreach loop
foreach ( $my_random_post as $post ) {
  // redirect the user to the random post
  wp_redirect ( get_permalink ( $post->ID ) );
  exit;
}

After you published the random page, any user who’ll visit the http://www.yourwebsite.com/randompage will be automatically redirected to a random post.

Source

 

Remove the Width and Height Attributes From WP Image Uploader

When you upload images via WordPress image uploader and insert it into your posts, WordPress automatically include the image width and height attributes in the html <img> tag. But when using a responsible theme, this can cause lots of trouble. Here’s a quick recipe to get rid of those attributes.

Simply paste the following code into your theme functions.php:

add_filter( 'post_thumbnail_html', 'remove_width_attribute', 10 );
add_filter( 'image_send_to_editor', 'remove_width_attribute', 10 );

function remove_width_attribute( $html ) {
   $html = preg_replace( '/(width|height)="\d*"\s/', "", $html );
   return $html;
}

Source

 

Display the Comment Stats in WordPress

This code will tell your advertisers or your audience, how many total comments your blog has, and an average number of comments on each post. Sometimes the per post number might be a decimal, but this code rounds it up to an integer value. You can also show this number in your sidebar as a statistic if you so desire.

All you have to do is paste the following code in a page where you want it displayed:

<?php
$count_posts = wp_count_posts();
$posts = $count_posts->publish;

$count_comments = get_comment_count();
$comments = $count_comments['approved'];

echo "There's a total of ".$comments." comments on my blog, with an average ".round($comments/$posts)." comments per post.";
?>

Source

 

Create a Drop Down List for Posts on WordPress

Just insert the following code into your theme — for example, in your sidebar. You can control the number of posts it displays by changing the number in this line of the code:

$args = array( 'numberposts' => -1);

To show all your posts, leave the “-1” in place. To show ten posts, for example, replace the “-1” with the number “10.”

<form action="<? bloginfo('url'); ?>" method="get">
 <select name="page_id" id="page_id">
 <?php
 global $post;
 $args = array( 'numberposts' => -1);
 $posts = get_posts($args);
 foreach( $posts as $post ) : setup_postdata($post); ?>
                <option value="<? echo $post->ID; ?>"><?php the_title(); ?></option>
 <?php endforeach; ?>
 </select>
 <input type="submit" name="submit" value="view" />
 </form>

Source

 

How to disable plugin updates on your WordPress blog

By default, WordPress automatically checks if plugins updates are available, and if yes, ask you to install it. It is useful in most cases, but when building websites for clients you may not want them to updates plugins, for example if you modified a plugin especially for them. Here is an easy way to disable plugin updates on any WordPress blog.

remove_action( 'load-update-core.php', 'wp_update_plugins' );
add_filter( 'pre_site_transient_update_plugins', create_function( '$a', "return null;" ) );

Source

 

Wordpress Hacks

 

Show Featured Images In Feed

To encourage subscribers to visit your website, rather than letting them just consume content through your RSS feed, you might want to display only the excerpt and featured image of posts. But WordPress doesn’t display the featured image in the RSS feed by default. Use the following code to do so. You can even add HTML to it.

add_filter('the_content_feed', 'rss_post_thumbnail');
function rss_post_thumbnail($content) {
	global $post;
	if( has_post_thumbnail($post->ID) )
		$content = '<p>' . get_the_post_thumbnail($post->ID, 'thumbnail') . '</p>' . $content;
	return $content;
}

Source

 

Grab tweets from twitter feed

Use this to quickly grab your tweets and display them anywhere on your site.

<?php
     try {
          $count = 6;
            $tweet=json_decode(file_get_contents("http://api.twitter.com/1/statuses/user_timeline/USERNAME.json?count=".$count."" ));
            for ($i=1; $i < $count; $i++){
                //Assign feed to $feed
                $feed = $tweet[($i-1)]->text;
                //Find location of @ in feed
                $feed = str_pad($feed, 3, ' ', STR_PAD_LEFT);   //pad feed
                $startat = stripos($feed, '@');
                $numat = substr_count($feed, '@');
                $numhash = substr_count($feed, '#');
                $numhttp = substr_count($feed, 'http');
                $feed = preg_replace("/(http://)(.*?)/([w./&=?-,:;#_~%+]*)/", "<a href=""></a>", $feed);
                $feed = preg_replace("(@([a-zA-Z0-9_]+))", "<a href="http://www.twitter.com/\1"></a>", $feed);
                $feed = preg_replace('/(^|s)#(w+)/', '1<a href="http://search.twitter.com/search?q=%232">#2</a>', $feed);
                echo "<div class='tweet'>".$feed.  "<div class='tweet_date'>". date("M - j",strtotime($tweet[($i-1)]->created_at))."
                        </div></div>";
                }
      } catch (Exception $e) {
          echo "Twitter feed is currently down, check back later.";
      }

?>

Source

 

Add a WordPress Menu To Your WordPress Toolbar

This WordPress snippet will add a WordPress Menu on the WordPress Toolbar.

add_action( 'admin_bar_menu', 'Add_Menu_To_Toolbar', 500 );
function Add_Menu_To_Toolbar(){
$menu< = wp_get_nav_menu_object( "Toolbar Menu" );
$menu_items = wp_get_nav_menu_items( $menu->term_id );

  foreach ($menu_items as $items) {
$args = array( 'id' =>  
$items->ID,
'title' =>      $items->title,
'parent' =>     $items->menu_item_parent,
'href' =>       $items->url,
'meta' =>       FALSE
;
$wp_admin_bar->add_node( $args );
}
}

Source

 

Display a Visitor’s Google Search Terms

If the visitor to the post or page has arrived via a Google search then display the terms that they searched for.

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

Source

 

Display your latest Google +1 update

This function can be used to display your latest Google +1 update anywhere in your WordPress website. Just insert the code below into your template files wherever you want it. Remember yo change the ID with your own.

<?php
	include_once(ABSPATH.WPINC.'/rss.php');
	$googleplus = fetch_feed("http://plusfeed.appspot.com/103329092193061943712"); // Replace 103329092193061943712 by your own ID
	echo '<a href="';
	echo $googleplus->items[0]['link']; echo '">';
	echo $googleplus->items[0]['summary'];
	echo '';
?>

Source

Keep WordPress from Compressing JPGs

Add the following code into your theme’s function.php file

add_filter('jpeg_quality', function($arg){return 100;});

Source

 

Increase the Excerpt Field Height

Simply paste the following code into your functions.php file. Height can be adjusted on line 5.

add_action('admin_head', 'excerpt_textarea_height');
function excerpt_textarea_height() {
    echo'
    <style type="text/css">
        #excerpt{ height:500px; }
    </style>
    ';
}

Source

 

Embed PDF in iframe

By adding the below code in your functions.php file and using the shortcode in the editor, the content of a PDF file can easily be embeded into the posts and pages of a WordPress website.

 function viewpdf($attr, $url) {
    return '<iframe src="http://docs.google.com/viewer?url=' . $url . '&embedded=true" style="width:' .$attr['width']. '; height:' .$attr['height']. ';" frameborder="0">Your browser should support iFrame to view this PDF document</iframe>';
}
add_shortcode('embedpdf', 'viewpdf');

Then in the post or page, use the shortcode to display the PDF.

[embedpdf width="600px" height="500px"]http://infolab.stanford.edu/pub/papers/google.pdf[/embedpdf]

Source

 

Add Custom Fields To RSS Feed

WordPress has the ability to add custom fields to any post, these fields allow you to store extra data about the post without it having to go into the content. You can use this data to add an extra piece of information to expand on your post. Here is a WordPress snippet to add to your functions.php file to display custom fields in your RSS feed:

function fields_in_feed($content) {
    if(is_feed()) {
        $post_id = get_the_ID();
        $output = '<div><h3>Find me on</h3>';
        $output .= '<p><strong>Facebook:</strong> ' . get_post_meta($post_id, 'facebook_url', true) . '</p>';
        $output .= '<p><strong>Google:</strong> ' . get_post_meta($post_id, 'google_url', true) . '</p>';
        $output .= '<p><strong>Twitter:</strong> ' . get_post_meta($post_id, 'twitter_url', true) . '</p>';
        $output .= '</div>';
        $content = $content.$output;
    }
    return $content;
}

add_filter('the_content','fields_in_feed');

Source

 

Automatically Set the Featured Image in WordPress

Add the following code into your functions.php file.The function will set the first image as featured image.

function autoset_featured() {
          global $post;
          $already_has_thumb = has_post_thumbnail($post->ID);
              if (!$already_has_thumb)  {
              $attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" );
                          if ($attached_image) {
                                foreach ($attached_image as $attachment_id => $attachment) {
                                set_post_thumbnail($post->ID, $attachment_id);
                                }
                           }
                        }
      }  //end function
add_action('the_post', 'autoset_featured');
add_action('save_post', 'autoset_featured');
add_action('draft_to_publish', 'autoset_featured');
add_action('new_to_publish', 'autoset_featured');
add_action('pending_to_publish', 'autoset_featured');
add_action('future_to_publish', 'autoset_featured');

Source

 

Import Content from an external file

If you want to import and display the content from an external file in your posts and pages you can do so by inserting the code below into your functions.php file:

function show_file_func( $atts ) {
extract( shortcode_atts( array(
'file' =&gt; ''
), $atts ) );

if ($file!='')
return @file_get_contents($file);
}

add_shortcode( 'show_file', 'show_file_func' );

Then in the editor use the shortcode like so:

[show_file file="http://www.yoursite.com/file345.html"]

Source

 

How to change the “posts” label to “articles”

Are you working for clients which aren’t very good with technology? If yes, most of them might find the term “post” a bit confusing, while “article” can be seen as much self-explanatory. Today, I’m going to show you how you can easily change the “post” label to “articles”. Nothing complicated: Open your functions.php file, paste the code below in it. Save the file, and you’re done!

add_filter('gettext',  'change_post_to_article');
add_filter('ngettext',  'change_post_to_article');

function change_post_to_article($translated) {
     $translated = str_ireplace('Post',  'Article',  $translated);
     return $translated;

Source

 

To stay up-to-date with the latest WordPress hacks or code snippets, follow me on Twitter, .. just saying ;-P

 

Author: Gonzo the Great

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. I also speak about webdesign and branding in the Netherlands.

4 comments

on this article: “15+ Useful and Fresh WordPress Hacks / Snippets”
  1. Thanks for these tips, certainly answers questions that I quite often have and they are a lot easier to read than the stuff on the main WordPress website!

    • Hi Jane,

      .. glad you liked these hacks! I try to share some of the hacks I found on different blogs, or hacks I need for client’s sites. I try to grab the essence of the hack and a easy-as-pie-way to embed them ;-P BTW: there are more articles on the gonzoblog.nl

      Have a great weekend, Cheers & Ciao ..

  2. Thank you thank you thank you! You are Gonzo the Great indeed! Just used the PDF embed hack for my resume and it works beautifully.

    • Hi Lauren,

      haha, it’s very pleasant to get reactions like these, very much appreciated! This is why I’m writing this blog, you just made my day Lauren! And glad you liked it and that it works like a charm! Send the URL, so we all can watch that hack in action ;-P

      Have a great one, cheers & ciao!

top