.. Your Daily Design Dosis

10+ Hacks to add functionality to your WordPress Theme

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

WordPress comes with standard functions but there are many plugins and code snippets/hacks to give your blog a different look and/or function(s). Today I have collected some new code snippets that focus on extending the functionality of WordPress even further.

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 script or virus.

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.

Having a collection of hacks and/or code snippets in your toolbox is very useful when developing WordPress Themes on a regular basis, depending on your needs you can make your WordPress blog more functional and dynamic with these code snippets. Not to mention the time you’ll save during the process of coding your theme. I hope you’ll enjoy my collection of code snippets .. let’s rock!

Move the Admin Bar to the Bottom

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

// move admin bar to bottom
function fb_move_admin_bar() { ?>
    <!--
        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: 28px;
        }
        <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;
        }

-->
// on backend area
add_action( 'admin_head', 'fb_move_admin_bar' );
// on frontend area
add_action( 'wp_head', 'fb_move_admin_bar' );

Source

Easily get post content by ID

When building a custom theme, you often need to get the content or title from a specific post. Sometimes, using a custom loop is the better option, but when you only to get information from a specific post, there’s a better option!

Simply use the get_post_field() function to get the post content. The following example will display the content of the post with id $post_id:

echo get_post_field('post_content', $post_id);

Source 

Remove Default WordPress Image Sizes

When you upload an image to WordPress by default it will be converted to three different sizes. You can remove these from being used by using the WordPress action intermediate_image_sizes_advanced and unset the thumbnail, medium and large sizes, this will mean the only size they have left is the full image size. Put this snippet into your function.php file.

function remove_default_image_sizes( $sizes) {
   unset( $sizes['thumbnail']); 
   unset( $sizes['medium']); 
   unset( $sizes['large']); 
   return $sizes; 
} 
add_filter('intermediate_image_sizes_advanced', 'remove_default_image_sizes');

Source

Make Your WordPress Post Look Nice When Shared On Facebook

The code allows you to set the “Featured Image” as the the image that Facebook shows when your link is shared. Secondly, it allows you to set a default image, in case your post does not make use of a “featured image”. You can use your logo for this default, by saving it in your themes directory, in a /images/ directory with the file name as default_icon.jpg. Or you can alter the image directory in the code below.

<!-- Begin FB Sharing for WP by Chad Von Lind. -->
<?php
	$thumb = get_post_meta($post->ID,'_thumbnail_id',false);
	$thumb = wp_get_attachment_image_src($thumb[0], false);
	$thumb = $thumb[0];
	$default_img = get_bloginfo('stylesheet_directory').'/images/default_icon.jpg';

	?>

<?php if(is_single() || is_page()) { ?>
	<meta property="og:type" content="article" />
	<meta property="og:title" content="<?php single_post_title(''); ?>" />
	<meta property="og:description" content="<?php 
	while(have_posts()):the_post();
	$out_excerpt = str_replace(array("\r\n", "\r", "\n"), "", get_the_excerpt());
	echo apply_filters('the_excerpt_rss', $out_excerpt);
	endwhile; 	?>" />
	<meta property="og:url" content="<?php the_permalink(); ?>"/>
	<meta property="og:image" content="<?php if ( $thumb[0] == null ) { echo $default_img; } else { echo $thumb; } ?>" />
<?php  } else { ?>
	<meta property="og:type" content="article" />
   <meta property="og:title" content="<?php bloginfo('name'); ?>" />
	<meta property="og:url" content="<?php bloginfo('url'); ?>"/>
	<meta property="og:description" content="<?php bloginfo('description'); ?>" />
    <meta property="og:image" content="<?php  if ( $thumb[0] == null ) { echo $default_img; } else { echo $thumb; } ?>" />
<?php  }  ?>
<!-- End FB Sharing for WP -->

Be Aware: Updating your code will not have immediate effects with Facebook, as Facebook will cache your shared link. It could take up to a few hours before the shared link would work properly. You can try to share one of your links that has not been shared before, to test that it is working proper.

Source

Automatically Create Meta Description From Content

In WordPress it can be done by using SEO plugins, but if you don’t have these plugins installed or forgot to add the meta description to this plugin then here is the WordPress snippet for you. This snippet will automatically take the first 125 characters of your content and add this into the meta description tag for the page.

function create_meta_desc() {
global $post;
if (!is_single()) { return; }
$meta = strip_tags($post-&gt;post_content);
$meta = strip_shortcodes($post-&gt;post_content);
$meta = str_replace(array("\n", "\r", "\t"), ' ', $meta);
$meta = substr($meta, 0, 125);
echo "&lt;meta name='description' content='$meta' /&gt;";
}
add_action('wp_head', 'create_meta_desc');

Source 

Add a Custom Database Error Page in WordPress

You ever remember seeing a screen like Error Establishing a Database Connection on your site. This can happen for various reasons, but often users don’t know that their site is down. We will show you how to customize your database error page in WordPress. We will also show you how to setup a notification for every time your website goes down due to a database error.

Open a new file and save it as “db-error.php”. Paste the following content inside that. Then upload the file in your /wp-content/ directory.

<?php // custom WordPress database error page

  header('HTTP/1.1 503 Service Temporarily Unavailable');
  header('Status: 503 Service Temporarily Unavailable');
  header('Retry-After: 600'); // 1 hour = 3600 seconds

  // If you wish to email yourself upon an error
  // mail("your@email.com", "Database Error", "There is a problem with the database!", "From: Db Error Watching");

?>

<!DOCTYPE HTML>
<html>
<head>
<title>Database Error</title>
<style>
body { padding: 20px; background: red; color: white; font-size: 60px; }
</style>
</head>
<body>
  You got problems.
</body>
</html>

If you want email notifications, then comment out the mail line. To comment it out, you have to remove // before the mail function.

Source

wordpress-code-snippets

List subpages and siblings

This is kind of a section navigation. It displays the current page’s subpages and siblings, if there are any. Should work anywhere in your theme.

<?php
    global $wp_query;
    if( empty($wp_query->post->post_parent) )
      {
         $parent = $wp_query->post->ID;
      }
    else
     {
         $parent = $wp_query->post->post_parent;
     } ?>
<?php if(wp_list_pages("title_li=&child_of=$parent&echo=0" )): ?>
    <div id="submenu">
     <ul>
      <?php wp_list_pages("title_li=&child_of=$parent" ); ?>
     </ul>
    </div>
<?php endif; ?>

Source

Display a custom message on WordPress registration page

If you need to be able to display a custom message on your registration page, here is a super simple solution to do it. First, update the code below with your message on line 6. Then, paste it into your functions.php file. You’re done! Just remove the code to remove the message if needed.

add_action('register_form', 'register_message');
function register_message() {
    $html = '
        <div style="margin:10px 0;border:1px solid #e5e5e5;padding:10px">
            <p style="margin:5px 0;">
            Joining this site you agree to the following terms. Do no harm!
            </p>
        </div>';
    echo $html;
}

Source

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

Remove menu items from WordPress admin bar

Here is a super useful code snippet for developers who wants to prevent their clients to access some dashboard menus, such as “Plugins” or “Settings”. Paste this code into your theme functions.php file to remove menus from the admin bar.

function wps_admin_bar() {
    global $wp_admin_bar;
    $wp_admin_bar->remove_menu('wp-logo');
    $wp_admin_bar->remove_menu('about');
    $wp_admin_bar->remove_menu('wporg');
    $wp_admin_bar->remove_menu('documentation');
    $wp_admin_bar->remove_menu('support-forums');
    $wp_admin_bar->remove_menu('feedback');
    $wp_admin_bar->remove_menu('view-site');
}
add_action( 'wp_before_admin_bar_render', 'wps_admin_bar' );

Source

WordPress function to get post/page slug

When coding or styling a theme, it can be very useful to be able to get the slug of the current post or page, for example to create a css class. Here’s an easy function to get the slug from the current post or page.

Here’s the function. Copy it and paste it into your functions.php file:

function the_slug() {
    $post_data = get_post($post->ID, ARRAY_A);
    $slug = $post_data['post_name'];
    return $slug; 
}

Once done, simply call the function within the loop to get the post or page slug.

<?php echo the_slug(); ?>

Source

Remove automatic link to WLW manifest file

Kind of pointless to include this unless you actually use Windows Live Writer to write your posts. Put this in the theme’s functions.php file.

remove_action( 'wp_head', 'wlwmanifest_link');

Source 

Integrate some Adsense Ads

Want to output some adsense ads in posts? Try this:

function adsense_shortcode( $atts ) {
	extract(shortcode_atts(array(
	    'format' => '1',
	), $atts));

	switch ($format) {
		case 1 :
			$ad = '<script type="text/javascript"><!--
			google_ad_client = "pub-6928386133078955";
			/* 234x60, created 16/09/08 */
			google_ad_slot = "0834408702";
			google_ad_width = 234;
			google_ad_height = 60;
			//-->
			</script>
			<script type="text/javascript"
			src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
			</script>';
		break;
	}
	return $ad;
}
add_shortcode('adsense', 'adsense_shortcode');

Remember to replace the adsense code with your own from google. Now you can output an ad simply using [adsense]. Add additional ad formats to the switch statement and you can output other ad formats using, for example, [adsense format=”2″].

Source

Display your latest Google+ update on your WordPress blog

Simply paste the following code where you want to display your latest Google+ update. Don’t forget to put your Google+ ID on line 3.

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

BONUS: Security Hack for your .HTACCESS file

Secure your WordPress blog uploads directory

As you probably have noticed gonzoblog.nl has got hacked a couple of months ago by an encrypted script that was added to an existing php-template of my blog. So let’s see how you can use a .htaccess file to secure your uploads directory and only accept specific files extensions.

If you don’t have an .htaccess file, create a file named .htaccess and paste the following code in it. Once done, upload the file into your wp-content/uploads directory.

The following example will only accept images files. If you need to be able to upload other file types, such as .pdf, don’t forget to add the file extension to the list on line 5.

<Files ~ ".*..*">
	Order Allow,Deny
	Deny from all
</Files>
<FilesMatch ".(jpg|jpeg|jpe|gif|png|tif|tiff)$">
	Order Deny,Allow
	Allow from all
</FilesMatch>

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: “10+ Hacks to add functionality to your WordPress Theme”
  1. I’m glad I found your blog. Just bookmarked it ;)
    Great hacks which I will surely use, thanks :)

    • Hi Marto,

      thanks for your comment, glad you liked some of the hacks! I try to post WP hacks every 2nd month here on the gonzoblog, so stay tuned ;-P

      Enjoy your weekend, cheers & ciao!

  2. Some useful stuff here. Might use some of them on my next project. Cheers.

    • Hi Caparico,

      glad to hear you liked my collection of WordPress snippets! Next month you can expect a new one .., yay!

      Have a great and successful week, thanks for commenting! Cheers & Ciao ..