.. Your Daily Design Dosis

15+ New and Useful WordPress Hacks / Code Snippets

| 6 Comments

One of the main reasons I like to work with WordPress is because it’s an open source Content Management System (CMS) that is easy to customize. With a few lines of code you can get some cool customization and new features with all those filters, actions and hooks.

In the last 2 months I have gathered these hacks because I needed some of them for ungoing WordPress projects or because they were mentioned on Twitter, Facebook, RSS Feeds, etc. All these code snippets should work in WordPress 3.0+, but 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.

There are a lot more WordPress hacks and/or code snippets here in the gonzoblog, take a look in our tag-list WordPress Hacks. In this article I’ld like to show you 16 useful code snippets and hacks that will help you extend the capabilities of your WordPress site, and of course save you time.

Hope you like them and that maybe some day, they’ll come to good use?

Display Recent Posts with Thumbnails

The piece of code is written in a minimal manner, but you can add divs and classes to stylize the widget. To make use of the thumbnails, firstly we need to activate them using the next piece of code in your function.php

<?php
if ( function_exists( 'add_theme_support' ) ) {
        add_theme_support( 'post-thumbnails' ); } //Adds thumbnails compatibility to the theme
set_post_thumbnail_size( 200, 170, true ); // Sets the Post Main Thumbnails
	add_image_size( 'recent-thumbnails', 55, 55, true ); // Sets Recent Posts Thumbnails
?>

Now that we have enabled post thumbnails, let’s write the function, inside the same functions.php file.

<ul>
<?php
function recentPosts() {
	$rPosts = new WP_Query();
	$rPosts->query('showposts=3);
		while ($rPosts->have_posts()) : $rPosts->the_post(); ?>
			<li>
				<a href="<?php the_permalink();?>"><?php the_post_thumbnail('recent-thumbnails'); ?></a>
				<h2><a href="<?php the_permalink(); ?>"><?php the_title();?></a></h2>
			</li>
		<?php endwhile;
	wp_reset_query();
}
?>
</ul>

In order to make it work, you have to call the function anywhere in your wordpress theme(single.php, footer.php, sidebar.php, etc), with the next line of code.

<?php echo recentPosts(); ?>

Source

Display the number of results in WordPress search

WordPress users know it: Search is definitely one of WordPress weak point. Today, let’s see how to get the number of results the search returned, and display it (proudly!) on our blog.

Open your search template file, search.php. In it, search for the following:

<h2>Search Results</h2>

Now replace this with:

<h2>Search Results for <?php /* Search Count */ $allsearch = &new WP_Query("s=$s&showposts=-1"); $key = wp_specialchars($s, 1); $count = $allsearch->post_count; _e(''); _e('<span>'); echo $key; _e('</span>'); _e(' — '); echo $count . ' '; _e('articles'); wp_reset_query(); ?></h2>

Source

Avoid Duplicate Post Display with Multiple Loops

The trick to avoiding duplicate post display is to store the post ID from the first loop, then check against that in the second loop. Here is how you do it. Your first loop’s code need to look like this (notice the magic line):

<?php $my_query = new WP_Query('category_name=featured&posts_per_page=1');
  while ($my_query->have_posts()) : $my_query->the_post();

  $do_not_duplicate = $post->ID; //This is the magic line

?>
    <!-- Do stuff... -->
<?php endwhile; ?>

Now that we have stored the post ID from the first loop under $do_not_duplicate variable, lets add a check for that in our second loop. Your second loop code should look something like this:

<?php if (have_posts()) : while (have_posts()) : the_post(); 

  if( $post->ID == $do_not_duplicate ) continue; //This is the Magic Line

 ?>
   <!-- Do stuff... -->
  <?php endwhile; endif; ?>

As long as you add those two lines in there, your posts will NOT replicate. To all new theme designers, we hope this helps.

Source

Automatically replace words by affiliate links

A simple piece of code that can replace words of your choice by an affiliate link. It’s simple, it’s free, and it works. I do not give you as much control as the plugins does, but in most cases this code should fit your needs.

Simply paste the code below into your functions.php file. Don’t forget to enter your words/links as shown in the example code.

function replace_text_wps($text){
    $replace = array(
        // 'WORD TO REPLACE' => 'REPLACE WORD WITH THIS'
        'thesis' => '<a href="http://mysite.com/myafflink">thesis</a>',
        'studiopress' => '<a href="http://mysite.com/myafflink">studiopress</a>'
    );
    $text = str_replace(array_keys($replace), $replace, $text);
    return $text;
}

add_filter('the_content', 'replace_text_wps');
add_filter('the_excerpt', 'replace_text_wps');

Source

Pull in the tags related to a category

This is a way to show all tags related to a category, without returning them in a list. This is a great way of adding more SEO, and kill some bounce rate.

Just make sure you change the name of your category where the category_name= starts. Use spaces if your category is named using more than one word. Put this code where you want the tags to be displayed.

<!--?php $project_query = query_posts('category_name=Real estate marketing'); while (have_posts()) : the_post();     $posttags = get_the_tags();     if ($posttags) {         foreach($posttags as $tag) {             $all_tags_arr[] = $tag ---> name; //USING JUST $tag MAKING $all_tags_arr A MULTI-DIMENSIONAL ARRAY, WHICH DOES WORK WITH array_unique
        }
    }
endwhile;

$tags_arr = array_unique($all_tags_arr); //REMOVES DUPLICATES
foreach( $tags_arr as $tag ):
    $el = get_term_by('name', $tag, 'post_tag');
    $arr[] = '"tag-'.$el->slug.'"';
?>
<span> <span>, </span></span>
<!--?php endforeach; ?-->

Source

Add Shortlink Menu Item in WordPress Admin Bar

With this hack, we will show you how you can add the Shortlink Menu back to your WordPress 3.3 admin bar. All you have to do is add the following line of code in your functions.php file:

add_action( 'admin_bar_menu', 'wp_admin_bar_shortlink_menu',90 );

Source

wordpress-code-snippets

Get Your Most Recent Twitter Status Using PHP

To find your numerical Twitter ID, login to Twitter and click on your RSS feed (bottom of the page). The URL will look something like http://twitter.com/statuses/friends_timeline/12345678.rss. Your ID will be the 12345678.

<?php
function get_status($twitter_id, $hyperlinks = true) {
    $c = curl_init();
    curl_setopt($c, CURLOPT_URL, "http://twitter.com/statuses/user_timeline/$twitter_id.xml?count=1");
    curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
    $src = curl_exec($c);
    curl_close($c);
    preg_match('/<text>(.*)</text>/', $src, $m);
    $status = htmlentities($m[1]);
    if( $hyperlinks ) $status = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]", "<a href="\0">\0</a>", $status);
    return($status);
}
?>

Source

Get thumbnail url

Here’s a snippet that gives you the ability to extract the source of the post thumbnail image. It is super useful if you need the post thumbnail url to use in your code. Simply paste the following code on your theme file, within the loop.

<?php
$image_id = get_post_thumbnail_id();
$image_url = wp_get_attachment_image_src($image_id);
$image_url = $image_url[0];
?>

Source

Display Post Views on WordPress Admin Posts Panel

Display the post views or counts on your Admins panel’s posts section. This is the place where you basically see all the post titles, authors, date, tags etc. Now, since we can display the post views for the visitors we can do the same thing for authors as well. This will help every single authors of your site to monitor their posts and its total number of views from the admin panel.

It’s a very simple concept. This snippet code will get the data (post views) from previous snippet code (function) and will display it inside the admin panel.

<?php
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); } }

add_filter('manage_posts_columns', 'posts_columns_id', 5);
add_action('manage_posts_custom_column', 'posts_custom_id_columns', 5, 2);
function posts_columns_id($defaults){
$defaults['post_views'] = __('Views');
return $defaults; }
function posts_custom_id_columns($column_name, $id){
if($column_name === 'post_views'){
echo getPostViews(get_the_ID());
} }
?>

Source

Show WordPress Pages on Your Homepage

If you ever wanted your Pages to show up in the stream of Posts on your homepage, then it’s easily done. Just add the following code to your functions.php file.

add_filter( 'pre_get_posts', 'my_get_posts' );
 function my_get_posts( $query ) {
 if ( is_home() && false == $query->query_vars['suppress_filters'] )
 $query->set( 'post_type', array( 'post', 'page') );
 return $query;
 }

Source

Block/reduce WordPress spam comments via .htaccess

Akismet key is a useful tool to prevent spam comments, however, it is not a possible solution for every WP site, so another easy (cut n paste) solution is this .htaccess snippet that blocks spam comments. Most spammers attack your site form wp-comments-post.php, at the same time you prevent extra load on your server.

Paste this code into your .htaccess file.

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_METHOD} POST
RewriteCond %{REQUEST_URI} .wp-comments-post.php*
RewriteCond %{HTTP_REFERER} !.*yourdomainname.* [OR]
RewriteCond %{HTTP_USER_AGENT} ^$
RewriteRule (.*) ^http://%{REMOTE_ADDR}/$ [R=301,L]
</IfModule>

Source

Limit Access by IP to Your wp-login.php file in WordPress

As a security measure, you can decide to limit access by IP to our wp-login.php file in WordPress. We already have our WP Admin directory on limited access by IP.

<Files wp-login.php>
order deny,allow
Deny from all

# whitelist West Palm Beach IP address
allow from xx.xxx.xx.xx

#whitelist Gainesvile IP Address
allow from xx.xxx.xx.xx

</Files>

Source

Custom Post Type Archives in WordPress Menus

Adds a simple Custom Post Type Archives metabox to the Menus, allowing you to add links to your post archives easily. Theme must support Menus. Paste in theme function.php file.

<?php
  add_action( 'admin_head-nav-menus.php', 'inject_cpt_archives_menu_meta_box');
  function inject_cpt_archives_menu_meta_box( $object ) {
    add_meta_box( 'add-cpt', __( 'CPT Archives' ), 'wp_nav_menu_cpt_archives_meta_box', 'nav-menus', 'side', 'default' );

    return $object; /* pass */
  }

  /* render custom post type archives meta box */
  function wp_nav_menu_cpt_archives_meta_box() {
    /* get custom post types with archive support */
    $post_types = get_post_types( array( 'show_in_nav_menus' => true, 'has_archive' => true ), 'object' );    

    /* hydrate the necessary object properties for the walker */
    foreach ( $post_types as &$post_type ) {
        $post_type->classes = array();
        $post_type->type = $post_type->name;
        $post_type->object_id = $post_type->name;
        $post_type->title = $post_type->labels->name . ' ' . __( 'Archive', 'default' );
        $post_type->object = 'cpt-archive';
    }

    $walker = new Walker_Nav_Menu_Checklist( array() );

    ?>
    <div id="cpt-archive">
      <div id="tabs-panel-cpt-archive">
        <ul id="ctp-archive-checklist">
          <?php
            echo walk_nav_menu_tree( array_map('wp_setup_nav_menu_item', $post_types), 0, (object) array( 'walker' => $walker) );
          ?>
        </ul>
      </div><!-- /.tabs-panel -->
    </div>
    <p>
      <span>
        <img src="<?php echo esc_url( admin_url( 'images/wpspin_light.gif' ) ); ?>" alt="" />
        <input type="submit"<?php disabled( $nav_menu_selected_id, 0 ); ?> value="<?php esc_attr_e('Add to Menu'); ?>" name="add-ctp-archive-menu-item" id="submit-cpt-archive" />
      </span>
    </p>
    <?php
  }

  add_filter( 'wp_get_nav_menu_items', 'cpt_archive_menu_filter', 10, 3 );
  function cpt_archive_menu_filter( $items, $menu, $args ) {
    /* alter the URL for cpt-archive objects */
    foreach ( $items as &$item ) {
      if ( $item->object != 'cpt-archive' ) continue;
      $item->url = get_post_type_archive_link( $item->type );
    }

    return $items;
  }
?>

Source

Embed a page into another page

Are you using different page templates on your WordPress theme? If yes, here is a cool hack that allow you to embed a page into another page. Paste the code below within the loop. Make sure to update page ID on line 1!

<?php $recent = new WP_Query("page_id=**ID**"); while($recent->have_posts()) : $recent->the_post();?>
       <h3><?php the_title(); ?></h3>
       <?php the_content(); ?>
<?php endwhile; ?>

Source

Exclude Categories from your RSS Feed in WordPress

To exclude specific categories from your RSS feed just add the following code snippet to your theme’s functions.php file. As always, make sure it is between PHP tags.

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

Source

Caching any custom query using transients

Using transients in your plugins and themes is simple and only adds a few extra lines of code, but if used in the right situations (long/expensive database queries or complex processed data) it can shave seconds off the load times on your site.

<?php
// Get any existing copy of our transient data
if ( false === ( $special_query_results = get_transient( 'special_query_results' ) ) ) {
    // It wasn't there, so regenerate the data and save the transient
     $special_query_results = new WP_Query( 'cat=5&order=random&tag=tech&post_meta_key=thumbnail' );
     set_transient( 'special_query_results', $special_query_results );
}

// Use the data like you would have normally...
?>

Source

 

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.

6 comments

on this article: “15+ New and Useful WordPress Hacks / Code Snippets”
  1. Very helpful code snippets. Thanks for sharing.

    • Hi Phelan,

      Glad you liked them .. hacks can make your life more simple! Have some more posts here on the gonzoblog, if you interested. Thanks for your comment,

      Cheers & Ciao ..!

  2. its such a great resource! actually it would be more useful for the blogger to use such codes! thanks for this nice share, i appreciated for that!

    • Hi Charlie,

      .. it is very useful to use these codes in your blogtheme than adding functionality by using plugins. The more plugins, the slower your blog gets, the more http-request are being sent out, more risk because you use 3rd-party codes (are they valide, clean and semanic?), less security issues because of ‘leaking’ plugins, etc., etc.

      I’m not saying that you shouldn’t use plugins at all (see: WordPress Plugins – The Most Wanted List.

      Thanks for your comment, Cheers & Ciao!