Home Web Internet Tips 22 Latest Exceptional WordPress Hacks

WordPress, by default, comes uncompressed and sends the uncompressed HTML to the visitor’s browser. With one line of code added to your header, you can compress WordPress’s output by up to 75%. By using zlib compression technology, you can harness the power of PHP and reduce your blog’s load time and increase the load speed!

First, place the following code in a file and call it “test.php” and then upload it to the root of your blog directory:

1 <?php phpinfo(); ?>

Make sure that “zlib” is enabled by your hosting provider.

Second, place the following code in your header (above the DOCTYPE):

1 <?php
2   ini_set('zlib.output_compression', 'On');
3   ini_set('zlib.output_compression_level', '1');
4 ?>

You’re done! Check Port80Software.com to ensure you are compressing your output.

Source Link

02. Allow More Time For Slow Servers to Upgrade WordPress

instantShift - Exceptional WordPress Hacks

WordPress auto download/install is a very nice feature, but sometimes a few problems can appear. One of them is that WordPress don’t manage to download the new version. This happens on slow servers. Here is how to solve it.

To apply this hack, you’ll have to edit one of WordPress core files. Keep in mind that it is never recommended. This hack should be applied only if you have problems while auto-upgrading WordPress.

Open the wp-admin/includes/files.php file and go to line 448. You’ll see the following:

1 $response = wp_remote_get($url, array('timeout' => 60));

To allow more downloading time, simply change the 60 with a greater value, as for example:

1 $response = wp_remote_get($url, array('timeout' => 120));

it’s all done!!

Source Link


Pages Related Hacks

03. How to Get All Custom Fields From a Page or a Post

instantShift - Exceptional WordPress Hacks

Sometimes you may need to get all custom fields from a specific post or page. Apply following function that do the job.

1 function all_my_customs($id = 0){
2   //if we want to run this function on a page of our choosing them the next section is skipped.
3   //if not it grabs the ID of the current page and uses it from now on.
4   if ($id == 0) :
5     global $wp_query;
6     $content_array = $wp_query->get_queried_object();
7     $id = $content_array->ID;
8   endif;  
10   //knocks the first 3 elements off the array as they are WP entries and i dont want them.
11   $first_array = array_slice(get_post_custom_keys($id), 3);
13   //first loop puts everything into an array, but its badly composed
14   foreach ($first_array as $key => $value) :
15     $second_array[$value] =  get_post_meta($id, $value, FALSE);
17     //so the second loop puts the data into a associative array
18     foreach($second_array as $second_key => $second_value) :
19       $result[$second_key] = $second_value[0];
20     endforeach;
21   endforeach;
23   //and returns the array.
24   return $result;
25 }

Once done, you can use the function like this:

1 $result = all_my_customs();
2 echo $result['my_meta_key'];

Source Link

04. How to Show Parent Page Title Regardless of What Subpage You Are On

instantShift - Exceptional WordPress Hacks

This hack is useful for peoples who working with WordPress as a CMS and wanting to be easily able to display parent page title on a subpage.

Nothing hard at all: Just paste the following code where you’d like to display the parent page title:

1 <?php
2 if($post->post_parent) {
3   $parent_title = get_the_title($post->post_parent);
4   echo $parent_title;
5 } else {
6   wp_title('');
7 }
8 ?>

That’s all! Quick and easy!!

Source Link

05. Display Guest Author Name in The Front Page and Individual Posts

instantShift - Exceptional WordPress Hacks

The first thing we need to do is to set a wordpress if statement to get the custom filed value. This way it will only show up when the custom file value is assigned. Open up your “index.php” and “single.php” and paste the following code where you want the author name to show up. It could be after date or after comments. For example after this code:

1 <?php the_time(’M j, Y’) ?>
1 <?php if ( get_post_meta($post->ID, 'guest_author_name', true) ) { ?>
2 // check to see if custom field guest author name exists
3 <?php echo get_post_meta($post->ID, "guest_author_name", $single = true); ?>
4 <?php } ?>

Once we put the if statement we just call it on whichever post we want the guest author name to show up. The guest author name should show up on the front page and for specified post only.

Source Link


Post Related Hacks

06. How to Display Content in Multiple Columns

instantShift - Exceptional WordPress Hacks

Printed magazines often display text in columns, so why blogs shouldn’t be able to do the same? here you can find out how to easily and automatically display your post content in columns.

This code is powerful but definitely easy to implement. Just paste it on your functions.php file and it will automatically output your post content in columns.
Your post content will be splitted on <h2> tags.

1 function my_multi_col($content){
2   $columns = explode('<h2>', $content);
4   $i = 0;
6     foreach ($columns as $column){
7     if (($i % 2) == 0){
8       $return .= '<div>' . "\n";
9       if ($i > 1){
10         $return .= "<h2>";
11       } else{
12         $return .= '<div>' . "\n <h2>";
13       }
14       $return .= $column;
15       $return .= '</h2></div>';
16       $i++;
17     }
19     if(isset($columns[1])){
20       $content = wpautop($return);
21     }else{
22       $content = wpautop($content);
23     }
24   echo $content;
25   }
26 }
27 add_filter('the_content', 'my_multi_col');
28 </h2>
29 </div>
30 </h2>

Don’t forget to add the following styles to your style.css file :

1 .content_right, .content_left{ 
2   float:left; 
3   width:45%; 
6 .content_left{ 
7   padding-right:5%; 
8 }

Source Link

07. How to Show WordPress Post Attachments

instantShift - Exceptional WordPress Hacks

Since WordPress 2.5, attachments management in WordPress have been improved and is now very powerful. Today, we’re going to show you a simple code snippet that you can use in your WordPress theme to display post attachments.

To achieve this recipe, just paste the following code anywhere in your post.php file and attachments will be displayed.

1 $args = array(
2   'post_type' => 'attachment',
3   'numberposts' => null,
4   'post_status' => null,
5   'post_parent' => $post->ID
6 );
7 $attachments = get_posts($args);
8 if ($attachments) {
9   foreach ($attachments as $attachment) {
10     echo apply_filters('the_title', $attachment->post_title);
11     the_attachment_link($attachment->ID, false);
12   }
13 }

Source Link

08. How to Set Post Expiration Date/Time on Your WordPress Blog

instantShift - Exceptional WordPress Hacks

Sometimes (for example, if you’re running a contest), you want to be able to publish a post and then automatically stop displaying it after a certain date. This may seem quite hard to do but in fact is not, using the power of custom fields.

Edit your theme and replace your current WordPress loop with this “hacked” loop:

1 <?php
2 if (have_posts()) :
3   while (have_posts()) : the_post(); ?>
4     $expirationtime = get_post_custom_values('expiration');
5     if (is_array($expirationtime)) {
6       $expirestring = implode($expirationtime);
7     }
9     $secondsbetween = strtotime($expirestring)-time();
10     if ( $secondsbetween > 0 ) {
11       // For example...
12       the_title();
13       the_excerpt();
14     }
15   endwhile;
16 endif;
17 ?>

To create a post set to expire at a certain date and time, just create a custom field. Specify expiration as a key and your date and time as a value (with the format mm/dd/yyyy 00:00:00). The post will not show up after the time on that stamp.

Note that this code does not remove or unpublish your post, but just prevents it from being displayed in the loop.

Source Link

09. How to Style Posts Individually

instantShift - Exceptional WordPress Hacks

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.

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 <p> </p>
5 <h3><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h3>
6 <?php the_content(); ?>
7 </div>
8 <?php endwhile; else: ?>
9 <?php _e('Sorry, no posts matched your criteria.'); ?>
10 <?php endif; ?>

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 Link

10. Display Content only to Registered Users in Your WordPress Blog

instantShift - Exceptional WordPress Hacks

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?

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

Source Link


Comment Page Related Hacks

11. How to Disable Comments in Old Posts via PHP

instantShift - Exceptional WordPress Hacks

In many situations like when you’re giving some alert to your readers or warning, and you don’t want to hear any feedback. Or you simply don’t want to have any comments, pingbacks, or trackbacks for respective event. For such situation you really want to know how to disable comments, pingbacks, and trackbacks via PHP in your WordPress blog.

The first step is to create it. Open your functions.php file and paste the following code:

1 <?php
2 function close_comments( $posts ) {
3   if ( !is_single() ) { return $posts; }
4   if ( time() - strtotime( $posts[0]->post_date_gmt ) > ( 30 * 24 * 60 * 60 ) ) {
5     $posts[0]->comment_status = 'closed';
6     $posts[0]->ping_status    = 'closed';
7   }
8   return $posts;
9 }
10 add_filter( 'the_posts', 'close_comments' );
11 ?>

You can run this script as a plugin, through your theme’s functions.php, or through a custom user-functions.php file. Simply set the desired number of days by changing the number “30” to whatever you would like. As is, this script will close comments, pingbacks and trackbacks on all articles posted more than 30 days ago.

Source Link

12. How to Display Registered Users Comment Count on Your Blog

instantShift - Exceptional WordPress Hacks

If your blog is private or have lots of registered users, it may be interesting to be able to display the number of comments posted by registered users. This is the purpose of this code.

Simply paste the following code where you’d like the count to be displayed. Re-arrange the code as desired.

1 <?php
2 global $wpdb;
3 $where = 'WHERE comment_approved = 1 AND user_id <> 0';
4 $comment_counts = (array) $wpdb->get_results("
5     SELECT user_id, COUNT( * ) AS total
6     FROM {$wpdb->comments}
7     {$where}
8     GROUP BY user_id
9   ", object);
10 foreach ( $comment_counts as $count ) {
11   $user = get_userdata($count->user_id);
12   echo 'User ' . $user->display_name . ' comment count is ' . $count->total . '';
13 }
14 ?>

That’s it! This will get approved comment count for each registered user.

Source Link

13. Separating Trackbacks From Comments in WordPress 2.7+

instantShift - Exceptional WordPress Hacks

Separating your trackbacks and comments requires a minimal amount of coding work to set up. First, you’ll want to make a backup of your comments.php file just in case something goes wrong. Next, follow these steps:

Access your comments.php file and locate the following code:

1 <?php foreach ($comments as $comment) : ?>

Immediately after the above code, you’ll want to place this code:

1 <?php $comment_type = get_comment_type(); ?>
2 <?php if($comment_type == 'comment') { ?>

Next, you’ll want to scroll down a little bit and locate the following code:

1 <?php endforeach; /* end for each comment */ ?>

Immediately before the above code, you’ll want to place this code:

1 <?php } /* End of is_comment statement */ ?>

This will filter out all of the trackbacks and pingbacks from your main comments loop. Now we need to create a second comments loop to display the trackbacks and pingbacks. Now, Almost immediately below the code from last step you should find this code:

1 <?php else : // this is displayed if there are no comments so far ?>

Immediately before the above code, you’ll want to place this code:

1 <p> </p>
2 <h3>Trackbacks</h3>
3 <ol>
4 <?php foreach ($comments as $comment) : ?>
5 <?php $comment_type = get_comment_type(); ?>
6 <?php if($comment_type != 'comment') { ?>
7 <li><?php comment_author_link() ?></li>
8 <?php } ?>
9 <?php endforeach; ?>
10 </ol>

Once you’ve got the comments successfully separated from the trackbacks, there are a couple additional tweaks you may want to do to clean up how things look (it really depends on preference I suppose). The first is to clean up your trackbacks/pingbacks by only displaying the title instead of an excerpt and everything else. In order to do this, you’ll need to find the following code in your comments.php file:

1 <ol>
2 <?php wp_list_comments('type=pings'); ?>
3 </ol>

Now replace that code with the following:

1 <ol>
2 <?php wp_list_comments('type=pings&callback=list_pings'); ?>
3 </ol>

Lastly, you’ll need to add the following code to your functions.php file (which can be created if you don’t already have one):

1 <?php
2 function list_pings($comment, $args, $depth) {
3   $GLOBALS['comment'] = $comment;
4 ?>
5 <li id="comment-<?php comment_ID(); ?>"><?php comment_author_link(); ?>
6 <?php } ?>
7 </li>

That should clean up the trackbacks/pingbacks section and you can also apply the same changes if you use a plugin to display tweetbacks.

The other thing you may want to do is fix the comment count to only show actual comments, filtering out the trackbacks/pingbacks which are included in your comment count by default. Simply add the following code to your functions.php file (which again can be created if you don’t already have one):

1 <?php
2 add_filter('get_comments_number', 'comment_count', 0);
3 function comment_count( $count ) {
4   if ( ! is_admin() ) {
5     global $id;
6     $comments_by_type = &separate_comments(get_comments('status=approve&post_id=' . $id));
7     return count($comments_by_type['comment']);
8   } else {
9     return $count;
10   }
11 }
12 ?>

So there you go. Now you have succesfully separated trackbacks from comments!

Source Link


Images Related Hacks

14. Automatically Resize Pictures on Your WordPress Blog

instantShift - Exceptional WordPress Hacks

You know it, a picture is worth a thousand words. But pictures means that you have to resize it, which is alwyas boring.
Happilly, a very cool script called TimThumb can resize pictures for you. The function below create a WordPress shortcode that will make Timthumb use even easier.

1 function imageresizer( $atts, $content = null ) {
2   return '<img src="/timthumb/timthumb.php?src='.$content.'&w=590" alt="">';
3 }
5 add_shortcode('img', 'imageresizer');

Then, 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]

Source Link


Social Networking and Email Related Hacks

15. How to Create a Tweetmeme “Retweeet” Shortcode

instantShift - Exceptional WordPress Hacks

Twitter is one of the best way to get quality traffic to your blog. In order to help people sharing your articles on Twitter, you should definitely implement a Tweetmeme button, which display how many time time people RT’d your blog posts.

Just paste the function below into your functions.php file.

1 function tweetmeme(){
2   return '&lt;div class=&quot;tweetmeme&quot;&gt;&lt;script type=&quot;text/javascript&quot; src=&quot;http://tweetmeme.com/i/scripts/button.js&quot;&gt;&lt;/script&gt;&lt;/div&gt;';
3 }
4 add_shortcode('tweet', 'tweetmeme');

Once you saved the file, you’ll be able to display the Tweetmeme “retweet” button anywhere on your posts. In WordPress editor, make sure you are in HTML mode and insert the following:

1 [tweet]

When your post will be published, the shortcode will be replaced by the TweetMeme button.

Source Link

16. Send Article to a Friend by Email

instantShift - Exceptional WordPress Hacks

In order to create more traffic on your blog, it can be a good idea to let your readers send your posts to their friends by email.

To apply this recipe to your blog, simply paste the following function into your functions.php file, and that’s all. Hard to do something simpler!

1 function direct_email($text=&quot;Send by email&quot;){
2   global $post;
3   $title = htmlspecialchars($post-&gt;post_title);
4   $subject = 'Sur '.htmlspecialchars(get_bloginfo('name')).' : '.$title;
5   $body = 'I recommend this page : '.$title.'. You can read it on : '.get_permalink($post-&gt;ID);
6   $link = '&lt;a rel=&quot;nofollow&quot; href=&quot;mailto:?subject='.rawurlencode($subject).'&amp;amp;body='.rawurlencode($body).'&quot; title=&quot;'.$text.' : '.$title.'&quot;&gt;'.$text.'&lt;/a&gt;';
7   return $link;
8 }

Source Link


Author Related Hacks

17. Automatically Insert Author Bio on Each Post

instantShift - Exceptional WordPress Hacks

When you’re owning a multi-writers blog, it is important to show who wrote the post. In case of guest bloggers, it is also a nice way to give credit.

Simply insert the following lines of code into your functions.php file, and that’s all. Author bio will be automatically displayed after each post.

1 function get_author_bio ($content=''){
2   global $post;
4   $post_author_name=get_the_author_meta("display_name");
5   $post_author_description=get_the_author_meta("description");
6   $html="
7 <div class="clearfix" id="about_author">\n";
8   $html.="<img width="80" height="80"plain">avatar" src="http://www.gravatar.com/avatar.php?gravatar_id=".md5(get_the_author_email()). "&default=".urlencode($GLOBALS[" defaultgravatar'])."&size="80&r=PG'" alt="PG">\n";
9   $html.="
10 <div class="author_text">\n";
11   $html.="
12 <h4>Author: <span>".$post_author_name."</span></h4>
14 \n";
15   $html.= $post_author_description."\n";
16   $html.="</div>
18 \n";
19   $html.="
20 <div class="clear"></div>
22 \n";
23   $content .= $html;
24   }
25   return $content;
26 }
28 add_filter('the_content', 'get_author_bio');
29 </div>

Source Link


Feeds Related Hacks

18. How to Fetch and Display RSS Feeds

instantShift - Exceptional WordPress Hacks

Do you know that WordPress have a built-in RSS reader? And you can use this feed to utilize in many ways. Here we’ll tell how to import and display feeds in wordPress 2.8 and beyond.

Simply paste the following code where you want the feed to be displayed. Don’t forget to define feed url at line 4.

1 <?php if(function_exists('fetch_feed')) {
3   include_once(ABSPATH.WPINC.'/feed.php');
4   $feed = fetch_feed('http://feeds.feedburner.com/catswhoblog');
6   $limit = $feed->get_item_quantity(7); // specify number of items
7   $items = $feed->get_items(0, $limit); // create an array of items
9 }
10 if ($limit == 0) echo '<div>The feed is either empty or unavailable.</div>';
11 else foreach ($items as $item) : ?>
13   <div>
14     <a href="<?php echo $item->get_permalink(); ?>" title="<?php echo $item->get_date('j F Y @ g:i a'); ?>">
15       <?php echo $item->get_title(); ?>
16     </a>
17   </div>
18   <div>
19     <?php echo substr($item->get_description(), 0, 200); ?>
20     <span>[...]</span>
21   </div>
23 <?php endforeach; ?>

Source Link


Category and Tags Related Hacks

19. How to Change Excerpt Length Depending of the Category

instantShift - Exceptional WordPress Hacks

Do you ever wished to be able to modify the excerpt length based on which category you are on, without modifying your theme files? If yes, we’re pretty sure you’ll be happy with this hack.

No need to modify your theme files. Simply paste the code into your functions.php file. Don’t forget to change the category ID on line 3!

1 add_filter('excerpt_length', 'my_excerpt_length');
2 function my_excerpt_length($length) {
3   if(in_category(14)) {
4     return 13;
5   } else {
6     return 60;
7   }
8 }

Source Link

20. Create a Function to Get Tags Related to Category

instantShift - Exceptional WordPress Hacks

First, here is the function you have to paste in your functions.php file:

1 function get_category_tags($args) {
2   global $wpdb;
3   $tags = $wpdb->get_results
4   ("
5     SELECT DISTINCT terms2.term_id as tag_id, terms2.name as tag_name, null as tag_link
6     FROM
7       wp_posts as p1
8       LEFT JOIN wp_term_relationships as r1 ON p1.ID = r1.object_ID
9       LEFT JOIN wp_term_taxonomy as t1 ON r1.term_taxonomy_id = t1.term_taxonomy_id
10       LEFT JOIN wp_terms as terms1 ON t1.term_id = terms1.term_id,
11       wp_posts as p2
12       LEFT JOIN wp_term_relationships as r2 ON p2.ID = r2.object_ID
13       LEFT JOIN wp_term_taxonomy as t2 ON r2.term_taxonomy_id = t2.term_taxonomy_id
14       LEFT JOIN wp_terms as terms2 ON t2.term_id = terms2.term_id
15     WHERE
16       t1.taxonomy = 'category' AND p1.post_status = 'publish' AND terms1.term_id IN (".$args['categories'].") AND
17       t2.taxonomy = 'post_tag' AND p2.post_status = 'publish'
18       AND p1.ID = p2.ID
19     ORDER by tag_name
20   ");
21   $count = 0;
22   foreach ($tags as $tag) {
23     $tags[$count]->tag_link = get_tag_link($tag->tag_id);
24     $count++;
25   }
26   return $tags;
27 }

Once you have pasted the function, you can use it in your theme:

1 $args = array('categories' => '12,13,14');
2 $tags = get_category_tags($args);

Source Link


Plugin Related Hacks

21. How to Create an Anti-IE6 Plugin

instantShift - Exceptional WordPress Hacks

With this amazing code created by Nathan Rice, you’ll be able to serve IE6 users the default WordPress theme. After all, those idiots don’t deserve anything better

Just paste the following in a new file and save it as ie6.php. Upload it to your wp-content/plugins directory and activate it on your WordPress dashboard.

1 <?php
2 /*
3 Plugin Name: Serve Default to IE6
4 Plugin URI: http://www.nathanrice.net/blog/serve-ie6-visitors-the-default-wordpress-theme
5 Description: This plugin will serve the default theme to any visitors using IE6.
6 Author: Nathan Rice
7 Author URI: http://www.nathanrice.net/
8 Version: 1.0
9 */
11 add_filter('template', 'serve_default_to_iesix');
12 add_filter('option_template', 'serve_default_to_iesix');
13 add_filter('option_stylesheet', 'serve_default_to_iesix');
14 function serve_default_to_iesix($theme) {
15   if(strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 6') !== false)
16     $theme = 'default';
17   return $theme;
18 }
19 ?>

Source Link

22. How to Check if a Plugin is Active or Not

instantShift - Exceptional WordPress Hacks

When working with lots and lots of plugins, it can be useful for developers to be able to check if a particular WordPress plugin is active or not. If you want to check if a WordPress plugin is active, just use the is_plugin_active() function. The function takes a single parameter, which is the path to the plugin, as shown in below:

1 <?php
2 if (is_plugin_active('plugin-directory/plugin-file.php')) {
3     //plugin is activated
4 }
5 ?>

Source Link

Hi, I spend most of my time working here in Briskblog, a blog solely focused on giving cool stuff about Wordpress, Internet tricks,Technology and entertainment. You can also connect me here: Google+