.. Your Daily Design Dosis

10+ great hacks to customize your WordPress Theme

| Comments Off on 10+ great hacks to customize your WordPress Theme

Today I’m posting some new, useful and awesome WordPress hacks and code snippets to make your blogger life easier. With a few lines you get some cool customization with all those filters, actions and hooks.

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.

With this in mind I have prepared for you some 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.

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 10+ new and useful code snippets/hacks that will help you extend the capabilities and functionalities of your WordPress site, I hope you’ll enjoy them?

Schedule cron jobs with WordPress

A cron job,  a task that’s triggered at predetermined intervals, let’s you run a bit of code at a specific interval, for example you could have a script that empty the trash can every hour. WordPress can do this for you with the wp_schedule_event() function.

add_action('my_hourly_event', 'do_this_hourly'); 

function my_activation() { 
   if ( !wp_next_scheduled( 'my_hourly_event' ) ) { 
        wp_schedule_event(time(), 'hourly', 'my_hourly_event'); 

add_action('wp', 'my_activation'); 

function do_this_hourly() { 
        // do something every hour 


Secure your WordPress blog uploads directory

Let’s see how you can use a .htaccess file to secure your uploads directory and only accept sepcific files extensions. Create a file named .htaccess and paste the following code in it. Once done, upload the filet 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
<FilesMatch ".(jpg|jpeg|jpe|gif|png|tif|tiff)$">
	Order Deny,Allow
	Allow from all


Enable TinyMCE for Post Excerpts Box

Here’s some neat code that will enable the TinyMCE rich text editor within your excerpts box. You can now insert links and other HTML into your excerpts. This code should be inserted into your theme’s functions.php, or better still create a plugin out of it.

function tinymce_excerpt_js(){ ?>
  <script type="text/javascript">
                jQuery(document).ready( tinymce_excerpt );
                    function tinymce_excerpt() {
                        tinyMCE.execCommand("mceAddControl", false, "excerpt");
                        tinyMCE.onAddEditor.add(function(mgr,ed) {
                                ed.settings.theme_advanced_buttons2 ="";
                                ed.settings.theme_advanced_buttons1 = "bold,italic,underline,seperator,justifyleft,justifycenter,justifyright,separator,link,unlink,seperator,pastetext,pasteword,removeformat,seperator,undo,redo,seperator,spellchecker,";
    <?php }
    add_action( 'admin_head-post.php', 'tinymce_excerpt_js');
    add_action( 'admin_head-post-new.php', 'tinymce_excerpt_js');
    function tinymce_css(){ ?>
        <style type='text/css'>
                    #postexcerpt .inside{margin:0;padding:0;background:#fff;}
                    #postexcerpt .inside p{padding:0px 0px 5px 10px;}
                    #postexcerpt #excerpteditorcontainer { border-style: solid; padding: 0; }
    <?php }
    add_action( 'admin_head-post.php', 'tinymce_css');
    add_action( 'admin_head-post-new.php', 'tinymce_css');

    function prepareExcerptForEdit($e){
        return nl2br($e);
    add_action( 'excerpt_edit_pre','prepareExcerptForEdit');


Search within a specific post type only

By default, when a visitor search on your site using WordPress built-in search engine, it search through all post types. But on some websites, you may want to be able to search only within a specific post type. Here’s a handy code snippet to do it. Simply update the code with your post type name on line 4, then paste it into your theme functions.php file.

function SearchFilter($query) {
  if ($query->is_search) {
    // Insert the specific post type you want to search
    $query->set('post_type', 'feeds');
  return $query;

// This filter will jump into the loop and arrange our results before they're returned


Keep Your Blog from Pinging Itself

It’s nice to get trackbacks from sites that have linked to your article. It’s not nice to get pinged every time you link within your own website. Before you reach for that plugin, try adding this simple snippet to your functions.php.

function disable_self_ping( &$links ) {
foreach ( $links as $l => $link )
if ( 0 === strpos( $link, get_option( 'home' ) ) )
add_action( 'pre_ping', 'disable_self_ping' );


Set Minimum Word Count On Posts

With WordPress there is an action hook on the publishing of a post called publish_post, using this hook you can create a function to make sure you have a minimum number of words in your post. To count the number of words in the post you need to get the current post content and use the PHP function str_word_count() to get the total number of words.  You can check to see if the post is under 500 words and if it is you can end the publishing process so the post will not be released.

function minimum_number_words($content)
global $post; 
$content = $post->post_content; 
if (str_word_count($content) < 500 ) 
wp_die( __('The current post is below the minimum number of words, it must be over 500 words.') ); 
add_action('publish_post', 'minimum_number_words');



Redirect to single post page if there is one post in category/tag

Archive indexes are a good way to organize your posts, but if there is only one post in an archive page it can be just a waste of time. Here i will give you a small #snippet to jump directly to the post page. To achieve this we will use wp_redirect which is a great feature for contexual template redirections. Here is the code to put in your functions.php file to jump single post archives:

function stf_redirect_to_post(){
    global $wp_query;
    // If there is one post on archive page
    if( is_archive() &amp;&amp; $wp_query-&gt;post_count == 1 ){
        // Setup post data
        // Get permalink
        $post_url = get_permalink();         
        // Redirect to post page
        wp_redirect( $post_url);
add_action('template_redirect', 'stf_redirect_to_post');


Display snapshots of external websites using a shortcode

Are you showcasing websites on your blog? If yes, you may find very useful to be able to put a snapshot of any website just by using a shortcode and the website url. This code, created by Ben Gillbanks and initially released as a plugin, will do the job perfectly. Let’s start by adding the functions below into your functions.php file.

function bm_sc_mshot ($attributes, $content = '', $code = '') {

		'url' => '',
		'width' => 250,
	), $attributes));
	$imageUrl = bm_mshot ($url, $width);
	if ($imageUrl == '') {
		return '';
	} else {
		$image = '<img src="' . $imageUrl . '" alt="' . $url . '" width="' . $width . '"/>';
		return '<div><a href="' . $url . '">' . $image . '</a></div>';

function bm_mshot ($url = '', $width = 250) {

	if ($url != '') {
		return 'http://s.wordpress.com/mshots/v1/' . urlencode(clean_url($url)) . '?w=' . $width;
	} else {
		return '';

add_shortcode('browsershot', 'bm_sc_mshot');

Once done, you can use the [browsershot] shortcode on WordPress editor, as shown below:

[browsershot url="http://link-to-website" width="foo-value"]


Load jQuery in the footer

By default, WordPress loads the jQuery javascript framework at the top of your files. Here’s a snippet to force WP to load jQuery in the theme footer. Paste the following code in your functions.php file, save it, and you’re done.

function ds_print_jquery_in_footer( &$scripts) {
	if ( ! is_admin() )
		$scripts->add_data( 'jquery', 'group', 1 );
add_action( 'wp_default_scripts', 'ds_print_jquery_in_footer' );


Change Posts Text In Admin Menu

Now that WordPress has all the capabilities you need from a CMS, many people say that they want WordPress to stop acting like a blog platform and more like a CMS.  A good way is to remove the word posts from the admin screen and replace this with the word article, in this tutorial you will learn how to do exactly that. This snippet will change the post in the menu to the Articles it will also get the sub-menus and change the labels to go from posts to articles.

* Change the post menu to article 

function change_post_menu_text() { 
   global $menu; 
   global $submenu; 
   // Change menu item 
   $menu[5][0] = 'Articles'; 
   // Change post submenu 
   $submenu['edit.php'][5][0] = 'Articles'; 
   $submenu['edit.php'][10][0] = 'Add Articles'; 
   $submenu['edit.php'][16][0] = 'Articles Tags'; 
add_action( 'admin_menu', 'change_post_menu_text' );

When you add a new post there is a header saying add post this snippet will change it to new Article. This will also change all the places post comes up and change it to article.

* Change the post type labels 

function change_post_type_labels() { 
   global $wp_post_types; 
   // Get the post labels 
   $labels = &$wp_post_types['post']->labels; 
   $labels->name = 'Articles'; 
   $labels->singular_name = 'Articles'; 
   $labels->add_new = 'Add Articles'; 
   $labels->add_new_item = 'Add Articles'; 
   $labels->edit_item = 'Edit Articles'; 
   $labels->new_item = 'Articles'; 
   $labels->view_item = 'View Articles'; 
   $labels->search_items = 'Search Articles'; 
   $labels->not_found = 'No Articles found'; 
   $labels->not_found_in_trash = 'No Articles found in Trash';
add_action( 'init', 'change_post_type_labels' );


Automatic “Nofollow” for external links in post content

By default, WordPress does not automatically add a rel="nofollow" attribute to external links within post content. Paste the following code snippet in your functions.php file. Once you saved the file, all external links in your post content will be changed to nofollow.

add_filter('the_content', 'auto_nofollow');

function auto_nofollow($content) {
    //return stripslashes(wp_rel_nofollow($content));

    return preg_replace_callback('/<a>]+/', 'auto_nofollow_callback', $content);

function auto_nofollow_callback($matches) {
    $link = $matches[0];
    $site_link = get_bloginfo('url');

    if (strpos($link, 'rel') === false) {
        $link = preg_replace("%(href=S(?!$site_link))%i", 'rel="nofollow" $1', $link);
    } elseif (preg_match("%href=S(?!$site_link)%i", $link)) {
        $link = preg_replace('/rel=S(?!nofollow)S*/i', 'rel="nofollow"', $link);
    return $link;


Hide theme editor from WordPress dashboard

If you’re a freelancer who often install WordPress on your clients websites, chances are that you don’t want them to be able to edit their theme. Here is a simple code snippet to hide the Theme Editor link from the dashboard so you can be sure that your clients won’t destroy their theme. Simply paste the following code on the theme functions.php file. Specify the admin username on line 7 so the admin will still see the theme editor link.

function wpr_remove_editor_menu() {
  remove_action('admin_menu', '_add_themes_utility_last', 101);

global $remove_submenu_page, $current_user;
if($current_user->user_login == 'admin') { //Specify admin name here
    add_action('admin_menu', 'wpr_remove_editor_menu', 1);



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.

Sorry, comments for this entry are closed at this time.