.. Your Daily Design Dosis

15 Fresh and Useful WordPress Hacks/Snippets

| 2 Comments

Despite of some brilliant WordPress plugins you really should use, there are situations when plugins could become an unnecessary problem, causing longer loadtime, including non-validated codes, not working scripts, etc.. The point is any plugin can crash your WordPress website functionality in some cases, or even worse, an (not updated) plugin could be a possible backdoor for hackers to start an attack, and infect your database with some kind of scrypt or virus.

When coding WordPress themes, especially if you do it regularly, it could be useful to have a selection of code snippets in your toolbox to just ‘copy and paste’ when a specific functionality is needed. With this in mind we have prepared for you some short and interesting WordPress snippets/hacks , most of these hacks can be pasted into your functions.php, this file is one of the most useful and important files in your theme. But before I begin, as always, a 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.

So, looking for simple and interesting solutions to improve your WordPress themes functionality? Well, here are some snippets for you, .. let’s rock!

How To Move the Admin Bar to the Bottom

Copy and paste this code and place it on your functions.php

<?php // move admin bar to bottom
function fb_move_admin_bar() { ?>

<style type="text/css">
body { margin-top: -28px; padding-bottom: 28px; }
body.admin-bar <a href="http://search.twitter.com/search?q=%23wphead" class="tweet-hashtag">#wphead</a> { padding-top: 0; }
body.admin-bar <a href="http://search.twitter.com/search?q=%23footer" class="tweet-hashtag">#footer</a> { padding-bottom: 28p; }
<a href="http://search.twitter.com/search?q=%23wpadminbar" class="tweet-hashtag">#wpadminbar</a> { top: auto !important; bottom: 0; }
<a href="http://search.twitter.com/search?q=%23wpadminbar" class="tweet-hashtag">#wpadminbar</a> .quicklinks .menupop ul { bottom: 28px; }
</style>
<!--?php }
// on backend area
add_action( 'admin_head', 'fb_move_admin_bar' );
// on frontend area
add_action( 'wp_head', 'fb_move_admin_bar' );

Source

Change excerpt length depending of the category

Ever wished to modify the excerpt length based on which category you are on? Here comes the code which grants your wish. Simply paste the code into your functions.php file, and don’t forget to change the category ID on line 3!

add_filter('excerpt_length', 'my_excerpt_length');
function my_excerpt_length($length) {
if(in_category(14)) {
return 13;
} else {
return 60;
}
}

Source

How To Add More Button on Visual Mode WordPress Editor

Open functions.php on your current theme using your favorite editor and add this code.

function add_more_buttons($buttons) { 
$buttons[] = 'hr'; 
$buttons[] = 'del'; 
$buttons[] = 'sub';
$buttons[] = 'sup';
$buttons[] = 'fontselect';
$buttons[] = 'fontsizeselect';
$buttons[] = 'cleanup'; 
$buttons[] = 'styleselect';
return $buttons;
}
add_filter("mce_buttons_3", "add_more_buttons");

Source

Track post views without using a plugin

Are you curious about how many people are reading your posts? A few “view counts” plugins exists, but here’s a simple way to do this yourself. The first thing to do is to create the functions. Paste the code below into your functions.php file.

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

Then, paste the code below within the single.php within the loop:

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

Finally, 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

wordpress-code-snippets

How to Disable Self Trackbacks

Paste the following code to your functions.php file

function disable_self_ping( &$links) { 
foreach ( $links as $l => $link )
if ( 0 === strpos( $link, get_option( 'home' ) ) ) 
unset($links[$l]);
}

add_action( 'pre_ping', 'disable_self_ping' );

Source

Display number of Facebook fans in full text

If you have a Facebook page for your blog, you might want to display how many fans you have. The following snippet will display how many fans you have. Just paste it on any of your theme files, where you’d like the count to be displayed.

<?php
	$page_id = "YOUR PAGE-ID";
	$xml = @simplexml_load_file("http://api.facebook.com/restserver.php?method=facebook.fql.query&query=SELECT%20fan_count%20FROM%20page%20WHERE%20page_id=".$page_id."") or die ("a lot");
	$fans = $xml->page->fan_count;
	echo $fans;
?>

Source

How to Remove Admin Color Scheme Options in WordPress

So maybe you like the grey option for the WordPress admin color scheme but you think the blue is hideous and you hope that none of your users have set it to blue and forget how to change it back. Or maybe you’ve created your own custom color scheme for the admin and you don’t want it changed. Here’s a quick code snippet that will remove the option from Your Profile >> Personal Options. 

Add this to your functions.php file

function admin_color_scheme() {
   global $_wp_admin_css_colors;
   $_wp_admin_css_colors = 0;
}
add_action('admin_head', 'admin_color_scheme');

Source

WordPress Simple Numbered Pagination Without a Plugin

Just place this WordPlace code snippet into a search of archive template. I see a lot of wordpress sites use plugins and bloated php code to create simple pagination. This useful snippet is actually in the WordPress Codex, It seems alot of people do not know about it.

<?php
global $wp_query;

$big = 999999999; // need an unlikely integer

echo paginate_links( array(
	'base' => str_replace( $big, '%#%', get_pagenum_link( $big ) ),
	'format' => '?paged=%#%',
	'current' => max( 1, get_query_var('paged') ),
	'total' => $wp_query->max_num_pages
) );
?>

Source

How to Create Simpler Login URL in WordPress for Your Clients

When working with a non-technical client, you often end up telling them well the login url is yourdomain.com/wp-login.php. Some folks suggest /wp-admin/ instead of the wp-login.php url. Wouldn’t it be so much better if you can just tell your clients to go to yoursite.com/login/. Well, in this article, we will show you how to create simpler login URL in WordPress for your clients.

Open the .htaccess file and paste the following code above the WordPress rewrite rule

RewriteRule ^login$ http://yoursite.com/wp-login.php [NC,L]

Don’t forget to replace the domain name to your site’s domain. That’s it. Now you can suggest your clients to go to yourname.com/login/ rather than wp-login.php

Source

Add Extra Contact Methods to User Profiles

The user_contactmethods filter allows you to set and unset the contact info fields on the user profile page. The great thing about using this method is that WordPress looks after the creation and updating of the fields.

Let’s add fields for Twitter and Facebook info. Put this in your functions.php file:

add_filter('user_contactmethods', 'my_user_contactmethods');

function my_user_contactmethods($user_contactmethods){

$user_contactmethods['twitter'] = 'Twitter Username';

$user_contactmethods['facebook'] = 'Facebook Username';

return $user_contactmethods;

}

If you want to remove some fields, just unset them from the array:

function my_user_contactmethods($user_contactmethods){

unset($user_contactmethods['yim']);

unset($user_contactmethods['aim']);

unset($user_contactmethods['jabber']);

$user_contactmethods['twitter'] = 'Twitter Username';

$user_contactmethods['facebook'] = 'Facebook Username';

return $user_contactmethods;

}

To display the user’s info, simply use the get_user_meta function.

echo get_user_meta(1, 'twitter', true);

This will show the Twitter username for the user with an ID of 1. The true argument causes the data to be returned as a single value as opposed to an array.

Source

Use your blog gravatar as favicon

If you want to use your gravatar as your favicon then simply add the following code in your function.php file and modify.

<?php
function GravatarAsFavicon() {

//We need to establish the hashed value of your email address
$GetTheHash = md5(strtolower(trim('you@yourdomain.com')));
echo 'http://www.gravatar.com/avatar/' . $GetTheHash . '?s=16';
}
?>

Then add the following code in your header.php file

<strong><link rel="shortcut icon" href="<?php GravatarAsFavicon(); ?>" /></strong>

Source

Custom Logos for Login page and Admin

To change the WordPress logo on the Login Page and the WordPress icon in the Dashboard, just put this snippet into your function.php file.

//  Custom logos for Login page and Admin
function custom_admin_logo() {
    echo '
        <style type="text/css">
            #header-logo { background-image: url('.get_bloginfo('template_directory').'/path/to/images/admin-logo.png) !important; }
        </style>
    ';
}
add_action('admin_head', 'custom_admin_logo');

function custom_login_logo() {
    echo '<style type="text/css">
        h1 a { background-image:url('.get_bloginfo('template_directory').'/path/to/images/login-logo.png) !important; }
    </style>';
}

add_action('login_head', 'custom_login_logo');

Source

Move Bad Behavior javascript to footer

The WP plugin ‘Bad Behavior’ is a popular way to keep spambots and unwanted traffic off your website. Unfortunately, the plugin inserts javascript in the header. A simple piece of code added to functions.php moves the javascript to the footer of your website. Add the code to functions.php and click Save. Reload your WordPress site and check the footer.

 

// move Bad Behavior javascript to footer
remove_action('wp_head', 'bb2_insert_head');
add_action('wp_footer', 'bb2_insert_head');

Source

Speed up your blog by caching custom queries

Is your theme using custom queries? If so, you should definitely use WordPress Transients API to cache the queries and consequently speed up your blog. This snippet will show you how to cache any custom queries.

Nothing hard here: simply paste the following code where you need to execute a custom query to the database. Don’t forget to update the query on line 5!

<?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

How To inserting Google Maps into WordPress Posts/Pages without Plugin

we only need to write Google Maps shortcode and we can put our own maps with really easy ways. The first time is write down this code below in your theme functions.php and we need to put the shortcode in our post/page with some parameters.

//Google Maps Shortcode
function do_googleMaps($atts, $content = null) {
extract(shortcode_atts(array(
 "width" => '640',
 "height" => '480',
 "src" => '', $atts));
return '<iframe width="'.$width.'" height="'.$height.'" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="'.$src.'&amp;output=embed" ></iframe>';
}
add_shortcode("googlemap", "do_googleMaps");

You can change the width and height what ever you want. Just replace on the code above. Now it’s time to practice, to use this shortcode is easy, just write down

[googlemap width="200" height="200" src="[you_url]"]

You can Replace [you_url] with your Google Maps Link.

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.

2 comments

on this article: “15 Fresh and Useful WordPress Hacks/Snippets”
  1. Hi Jan,

    This is great info, very useful.

    I have one question;
    When you “Add Extra Contact Methods to User Profiles” to the functions.php file the fields show up in the Admin Panel -> User, but it seems that the extra contact info is not being saved to the WP database (wp-usemeta).

    Do you know if the extra contact info IS being saved to the WP db (maybe a other location) or is this not simply not possible. Maybe do you need some extra steps?

    There is a private WP function _wp_get_user_contactmethods in user.php @line 1484, but adding this info in here is not the right place if i understand correctly. Maybe an array_merge like @1472?

    Let me know what your thoughts are.

    • Hi Warner,

      Thanks for your comment .. and great question! Without any doubt the ‘new’ contact info is being saved in the database, otherwise you can’t fire the php command to echo get_user_meta. Being certain this info is saved in the wp_usermeta, but made curious by your remark, I did a quick (and simple) query in my database (if you use php-admin,go to the search tab w/i your database and write ‘twitter’ in the input field and select all tables).

      Et volia, the input of the twitter contact info should be in your wp_usermeta (or prefix_usermeta) table? If not, there is something wrong! I digged a bit further, cuz I also have this working on my blog (and other client projects) and found out I use another hack! Maybe you could try this one:

      /*-----------------------------------------------------------------------------------*/
      // modify contact info
      /*-----------------------------------------------------------------------------------*/
      function extra_contact_info($contactmethods) {
          unset($contactmethods['aim']);
          unset($contactmethods['yim']);
          unset($contactmethods['jabber']);
          $contactmethods['facebook'] = 'Facebook';
          $contactmethods['twitter'] = 'Twitter';
          $contactmethods['linkedin'] = 'LinkedIn';
       
          return $contactmethods;
      }
      add_filter('user_contactmethods', 'extra_contact_info');
      

      and if you wanna show these somewhere in your (author’s info) post then put these in your single.php:

      <a href="http://www.twitter.com/<?php the_author_meta('twitter'); ?">Twitter</a> 
      <a href="http://www.facebook.com/<?php the_author_meta('facebook'); ?">Facebook</a>   
      <a href="http://www.linkedin.com/in/<?php the_author_meta('linkedin'); ?">LinkedIn</a>
      

      Try this one, maybe it will bring you more luck? I know this one works fine for me .. maybe I’ll even update the hack in the post? Anyhowz, let me know if it works for you, okay? Cheers & Ciao!

top