Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Please vote on the question and any answers you find useful by clicking on the UP arrow on the left hand side of the question or answer.

As with many others who are now viewing this post, I have been reading various blogs, forums, and discussion groups to learn and improve my wordpress skills. Over the past 12 months I have been on a mission to substitute my use of plugins by adding code to my functions.php file instead. While I completely agree that plugins are very useful in many situations my experience proved that in 90% of usage cases although a plugin might exist, actually utilizing it could create unnecessary complications and compatibility issues. Additionally in a great deal of cases such plugins added menus and other admin elements which I don't want or need.

More often than not I have found that by analyzing the code of plugins I was able to strip out the piece of code I wanted and hard code it into my functions.php. This provided me with the exact functionality I needed without having to include unnecessary elements.

So, the purpose of this post is my attempt to engage you, the reader/admin/developer, to share with me and other here any code bits which you find useful and have added to your theme's function.php file to extend or enhance WordPress without utilizing a plugin.

When you submit a response here please kindly give each code bit a title, let us know if with what version of wordpress you know its compatible with, include whatever description you feel best describes its function and (if applicable) include a link to the original plugin or source where you found the information.

I am looking forward to all your responses and will of course continually add my own new finds whenever I find them.

share|improve this question

closed as not constructive by Rarst Feb 15 '12 at 12:44

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.If this question can be reworded to fit the rules in the help center, please edit the question.

10  
Considering the first 5 answers were by the OP and the question seems more geared at collecting an array of responses rather than a single, definitive answer, this should be a community wiki. –  EAMann Sep 9 '10 at 14:43
14  
All answers not related to a theme should be removed. This thread is a good example for bad coding practices. –  toscho Jun 13 '11 at 12:09
14  
I think it'd be better to encourage people to create a custom functionality plugin instead of using their theme's functions.php –  Ian Dunn Jan 16 '12 at 18:49
2  
@NetConstructor.com The pure number of page views is not an indicator for quality. We should encourage specific questions with specific answers and good coding practices. This thread is the opposite. –  toscho Feb 22 '12 at 2:44
5  
@NetConstructor.com Discuss it on Meta where people can see your arguments better. :) –  toscho Feb 24 '12 at 17:10

108 Answers 108

Enable Hidden Admin Feature displaying ALL Site Settings

Tested on: Wordpress 3.1 RC3

This little piece of code does something pretty cool. It will add an additional option to your settings menu with a link to "all settings" which will show you a complete list of all the settings you have within your database related to your wordpress site. The code below will only made this link visible to an admin user and hide it for all other users.

// CUSTOM ADMIN MENU LINK FOR ALL SETTINGS
   function all_settings_link() {
    add_options_page(__('All Settings'), __('All Settings'), 'administrator', 'options.php');
   }
   add_action('admin_menu', 'all_settings_link');
share|improve this answer

Modify the Login Logo & Image URL Link

Tested on: WordPress 3.0.1

This code will allow you to easily modify the WordPress Login page Logo as well as the href link and title text of this logo.

add_filter( 'login_headerurl', 'namespace_login_headerurl' );
/**
 * Replaces the login header logo URL
 *
 * @param $url
 */
function namespace_login_headerurl( $url ) {
    $url = home_url( '/' );
    return $url;
}

add_filter( 'login_headertitle', 'namespace_login_headertitle' );
/**
 * Replaces the login header logo title
 *
 * @param $title
 */
function namespace_login_headertitle( $title ) {
    $title = get_bloginfo( 'name' );
    return $title;
}

add_action( 'login_head', 'namespace_login_style' );
/**
 * Replaces the login header logo
 */
function namespace_login_style() {
    echo '<style>.login h1 a { background-image: url( ' . get_template_directory_uri() . '/images/logo.png ) !important; }</style>';
}

EDIT: If you want to use the site logo to replace the login logo, you can use the following to dynamically pull that information (tested on WP3.5):

function namespace_login_style() {
    if( function_exists('get_custom_header') ){
        $width = get_custom_header()->width;
        $height = get_custom_header()->height;
    } else {
        $width = HEADER_IMAGE_WIDTH;
        $height = HEADER_IMAGE_HEIGHT;
    }
    echo '<style>'.PHP_EOL;
    echo '.login h1 a {'.PHP_EOL; 
    echo '  background-image: url( '; header_image(); echo ' ) !important; '.PHP_EOL;
    echo '  width: '.$width.'px !important;'.PHP_EOL;
    echo '  height: '.$height.'px !important;'.PHP_EOL;
    echo '  background-size: '.$width.'px '.$height.'px !important;'.PHP_EOL;
    echo '}'.PHP_EOL;
    echo '</style>'.PHP_EOL;
}
share|improve this answer

Remove Update Notification for all users except ADMIN User

Tested on: Wordpress 3.0.1

This code will ensures that no users other than "admin" are notified by wordpress when updates are available..

// REMOVE THE WORDPRESS UPDATE NOTIFICATION FOR ALL USERS EXCEPT SYSADMIN
   global $user_login;
   get_currentuserinfo();
   if ($user_login !== "admin") { // change admin to the username that gets the updates
    add_action( 'init', create_function( '$a', "remove_action( 'init', 'wp_version_check' );" ), 2 );
    add_filter( 'pre_option_update_core', create_function( '$a', "return null;" ) );
   }

Changed version to only show update notification for admin users (as opposed to just the user 'admin'):

// REMOVE THE WORDPRESS UPDATE NOTIFICATION FOR ALL USERS EXCEPT SYSADMIN
       global $user_login;
       get_currentuserinfo();
       if (!current_user_can('update_plugins')) { // checks to see if current user can update plugins 
        add_action( 'init', create_function( '$a', "remove_action( 'init', 'wp_version_check' );" ), 2 );
        add_filter( 'pre_option_update_core', create_function( '$a', "return null;" ) );
       }
share|improve this answer
5  
This is far less than ideal. It will only work if the admin's login is still the default 'admin', which it shoudln't be for security reasons. Instead you should check for a specific capability that you want people to have to see messages. –  jeremyclarke Sep 11 '10 at 20:28
1  
I.e. if (!current_user_can('manage_options')) {...add_filter...} -- Sorry about double comment, I forgot that hitting enter submits comments) –  jeremyclarke Sep 11 '10 at 20:29
2  
so: if (!current_user_can('update_plugins')) {/*REMOVE MESSAGES*/} –  jeremyclarke Sep 12 '10 at 14:01

Include custom post types in the search results.

// MAKE CUSTOM POST TYPES SEARCHABLE
function searchAll( $query ) {
 if ( $query->is_search ) { $query->set( 'post_type', array( 'site', 'plugin', 'theme', 'person' )); } 
 return $query;
}
add_filter( 'the_search_query', 'searchAll' );

Add your custom post types to your sites main RSS feed by default.

// ADD CUSTOM POST TYPES TO THE DEFAULT RSS FEED
function custom_feed_request( $vars ) {
 if (isset($vars['feed']) && !isset($vars['post_type']))
  $vars['post_type'] = array( 'post', 'site', 'plugin', 'theme', 'person' );
 return $vars;
}
add_filter( 'request', 'custom_feed_request' );

Include custom post types in "Right Now" admin dashboard widget

This will include your custom post types and the post counts for each type in the "Right Now" dashboard widget.

// ADD CUSTOM POST TYPES TO THE 'RIGHT NOW' DASHBOARD WIDGET
function wph_right_now_content_table_end() {
 $args = array(
  'public' => true ,
  '_builtin' => false
 );
 $output = 'object';
 $operator = 'and';
 $post_types = get_post_types( $args , $output , $operator );
 foreach( $post_types as $post_type ) {
  $num_posts = wp_count_posts( $post_type->name );
  $num = number_format_i18n( $num_posts->publish );
  $text = _n( $post_type->labels->singular_name, $post_type->labels->name , intval( $num_posts->publish ) );
  if ( current_user_can( 'edit_posts' ) ) {
   $num = "<a href='edit.php?post_type=$post_type->name'>$num</a>";
   $text = "<a href='edit.php?post_type=$post_type->name'>$text</a>";
  }
  echo '<tr><td class="first num b b-' . $post_type->name . '">' . $num . '</td>';
  echo '<td class="text t ' . $post_type->name . '">' . $text . '</td></tr>';
 }
 $taxonomies = get_taxonomies( $args , $output , $operator ); 
 foreach( $taxonomies as $taxonomy ) {
  $num_terms  = wp_count_terms( $taxonomy->name );
  $num = number_format_i18n( $num_terms );
  $text = _n( $taxonomy->labels->singular_name, $taxonomy->labels->name , intval( $num_terms ));
  if ( current_user_can( 'manage_categories' ) ) {
   $num = "<a href='edit-tags.php?taxonomy=$taxonomy->name'>$num</a>";
   $text = "<a href='edit-tags.php?taxonomy=$taxonomy->name'>$text</a>";
  }
  echo '<tr><td class="first b b-' . $taxonomy->name . '">' . $num . '</td>';
  echo '<td class="t ' . $taxonomy->name . '">' . $text . '</td></tr>';
 }
}
add_action( 'right_now_content_table_end' , 'wph_right_now_content_table_end' );
share|improve this answer

Loading jQuery from the Google CDN

Tested on: Wordpress 3.0.1

// even more smart jquery inclusion :)
add_action( 'init', 'jquery_register' );

// register from google and for footer
function jquery_register() {

if ( !is_admin() ) {

    wp_deregister_script( 'jquery' );
    wp_register_script( 'jquery', ( 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js' ), false, null, true );
    wp_enqueue_script( 'jquery' );
}
}

Remove the WordPress Version Info for Security

Tested on: Wordpress 3.0.1

// remove version info from head and feeds
function complete_version_removal() {
    return '';
}
add_filter('the_generator', 'complete_version_removal');

Add Spam & Delete Links to Comments on Front End

Tested on: Wordpress 3.0.1

This makes it way easier to manage comments from the front end by adding spam and delete links.**

// spam & delete links for all versions of wordpress
function delete_comment_link($id) {
    if (current_user_can('edit_post')) {
        echo '| <a href="'.get_bloginfo('wpurl').'/wp-admin/comment.php?action=cdc&c='.$id.'">del</a> ';
        echo '| <a href="'.get_bloginfo('wpurl').'/wp-admin/comment.php?action=cdc&dt=spam&c='.$id.'">spam</a>';
    }
}

Delay the public posting to RSS Feed

Tested on: Wordpress 3.0.1

Finally, I like to delay posting to my RSS feeds for 10-15 minutes because I always find at least a couple errors in my text. Other uses are in case you want content to be exclusive to your site for a day or a week before pushing it out to your RSS readers.

// delay feed update
function publish_later_on_feed($where) {
    global $wpdb;

    if (is_feed()) {
        // timestamp in WP-format
        $now = gmdate('Y-m-d H:i:s');

        // value for wait; + device
        $wait = '10'; // integer

        // http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_timestampdiff
        $device = 'MINUTE'; // MINUTE, HOUR, DAY, WEEK, MONTH, YEAR

        // add SQL-sytax to default $where
        $where .= " AND TIMESTAMPDIFF($device, $wpdb->posts.post_date_gmt, '$now') > $wait ";
    }
    return $where;
}
add_filter('posts_where', 'publish_later_on_feed');
share|improve this answer
1  
You can also just remove the generator filter: remove_action('wp_head', 'wp_generator'); –  Gipetto Sep 18 '10 at 7:01
25  
ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js expires after just one hour. Always use the full version information like ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js – that expires after one year. –  toscho Nov 10 '10 at 14:41
5  
The "Remove the WordPress Version Info for Security" code doesn't actually do anything to increase the security of your site. It doesn't even stop exposure of the WP version being used on your site. –  Joseph Scott Feb 11 '11 at 6:38

Wordpress Profiling tools

I like to add profiling tools in a separate file, which I then include from functions.php when needed:

<?php
if ( !defined('SAVEQUERIES') && isset($_GET['debug']) && $_GET['debug'] == 'sql' )
    define('SAVEQUERIES', true);
if ( !function_exists('dump') ) :
/**
 * dump()
 *
 * @param mixed $in
 * @return mixed $in
 **/

function dump($in = null) {
    echo '<pre style="margin-left: 0px; margin-right: 0px; padding: 10px; border: solid 1px black; background-color: ghostwhite; color: black; text-align: left;">';
    foreach ( func_get_args() as $var ) {
        echo "\n";
        if ( is_string($var) ) {
            echo "$var\n";
        } else {
            var_dump($var);
        }
    }
    echo '</pre>' . "\n";
    return $in;
} # dump()
endif;

/**
 * add_stop()
 *
 * @param mixed $in
 * @param string $where
 * @return mixed $in
 **/

function add_stop($in = null, $where = null) {
    global $sem_stops;
    global $wp_object_cache;
    $queries = get_num_queries();
    $milliseconds = timer_stop() * 1000;
    $out =  "$queries queries - {$milliseconds}ms";
    if ( function_exists('memory_get_usage') ) {
        $memory = number_format(memory_get_usage() / ( 1024 * 1024 ), 1);
        $out .= " - {$memory}MB";
    }
    $out .= " - $wp_object_cache->cache_hits cache hits / " . ( $wp_object_cache->cache_hits + $wp_object_cache->cache_misses );
    if ( $where ) {
        $sem_stops[$where] = $out;
    } else {
        dump($out);
    }
    return $in;
} # add_stop()


/**
 * dump_stops()
 *
 * @param mixed $in
 * @return mixed $in
 **/

function dump_stops($in = null) {
    if ( $_POST )
        return $in;
    global $sem_stops;
    global $wp_object_cache;
    $stops = '';
    foreach ( $sem_stops as $where => $stop )
        $stops .= "$where: $stop\n";
    dump("\n" . trim($stops) . "\n");
    if ( defined('SAVEQUERIES') && $_GET['debug'] == 'sql' ) {
        global $wpdb;
        foreach ( $wpdb->queries as $key => $data ) {
            $query = rtrim($data[0]);
            $duration = number_format($data[1] * 1000, 1) . 'ms';
            $loc = trim($data[2]);
            $loc = preg_replace("/(require|include)(_once)?,\s*/ix", '', $loc);
            $loc = "\n" . preg_replace("/,\s*/", ",\n", $loc) . "\n";
            dump($query, $duration, $loc);
        }
    }
    if ( $_GET['debug'] == 'cache' )
        dump($wp_object_cache->cache);
    if ( $_GET['debug'] == 'cron' ) {
        $crons = get_option('cron');
        foreach ( $crons as $time => $_crons ) {
            if ( !is_array($_crons) )
                continue;
            foreach ( $_crons as $event => $_cron ) {
                foreach ( $_cron as $details ) {
                    $date = date('Y-m-d H:m:i', $time);
                    $schedule = isset($details['schedule']) ? "({$details['schedule']})" : '';
                    if ( $details['args'] )
                        dump("$date: $event $schedule", $details['args']);
                    else
                        dump("$date: $event $schedule");
                }
            }
        }
    }
    return $in;
} # dump_stops()
add_action('init', create_function('$in', '
    return add_stop($in, "Load");
    '), 10000000);
add_action('template_redirect', create_function('$in', '
    return add_stop($in, "Query");
    '), -10000000);
add_action('wp_footer', create_function('$in', '
    return add_stop($in, "Display");
    '), 10000000);
add_action('admin_footer', create_function('$in', '
    return add_stop($in, "Display");
    '), 10000000);

/**
 * init_dump()
 *
 * @return void
 **/

function init_dump() {
    global $hook_suffix;
    if ( !is_admin() || empty($hook_suffix) ) {
        add_action('wp_footer', 'dump_stops', 10000000);
        add_action('admin_footer', 'dump_stops', 10000000);
    } else {
        add_action('wp_footer', 'dump_stops', 10000000);
        add_action("admin_footer-$hook_suffix", 'dump_stops', 10000000);
    }
} # init_dump()
add_action('wp_print_scripts', 'init_dump');


/**
 * dump_phpinfo()
 *
 * @return void
 **/

function dump_phpinfo() {
    if ( isset($_GET['debug']) && $_GET['debug'] == 'phpinfo' ) {
        phpinfo();
        die;
    }
} # dump_phpinfo()
add_action('init', 'dump_phpinfo');


/**
 * dump_http()
 *
 * @param array $args
 * @param string $url
 * @return array $args
 **/

function dump_http($args, $url) {
    dump(preg_replace("|/[0-9a-f]{32}/?$|", '', $url));
    return $args;
} # dump_http()


/**
 * dump_trace()
 *
 * @return void
 **/

function dump_trace() {
    $backtrace = debug_backtrace();
    foreach ( $backtrace as $trace )
        dump(
            'File/Line: ' . $trace['file'] . ', ' . $trace['line'],
            'Function / Class: ' . $trace['function'] . ', ' . $trace['class']
            );
} # dump_trace()
if ( $_GET['debug'] == 'http' )
    add_filter('http_request_args', 'dump_http', 0, 2);
?>
share|improve this answer
1  
That's how it's done in my theme: semiologic.com/software/sem-reloaded -- the /inc/debug.php is included by /functions.php or /inc/init.php (can't recall off the top of my head). –  Denis Feb 23 '11 at 9:50

Set a maximum number of post revisions to avoid DB bloat.

Tested on: Wordpress 3.0.1

Default is infinite, this will set it to only remember last 5 edits:

/**
 * Set the post revisions unless the constant was set in wp-config.php
 */
if (!defined('WP_POST_REVISIONS')) define('WP_POST_REVISIONS', 5);

FWIW there are a ton of great ideas for CONSTANTS that can be set on the Codex page Editing wp-config.php.

share|improve this answer
1  
personally I prefer 10. I know it's double but always when I need a revision it's always older then 5 –  janw Sep 4 '12 at 12:04

Remove Default Wordpress Meta Boxes

Tested on: Wordpress 3.0.1

This code will allow you to remove specific Meta Boxes which wordpress adds by default to the default Add/Edit Post and Add/Edit Page screens.

// REMOVE META BOXES FROM DEFAULT POSTS SCREEN
   function remove_default_post_screen_metaboxes() {
 remove_meta_box( 'postcustom','post','normal' ); // Custom Fields Metabox
 remove_meta_box( 'postexcerpt','post','normal' ); // Excerpt Metabox
 remove_meta_box( 'commentstatusdiv','post','normal' ); // Comments Metabox
 remove_meta_box( 'trackbacksdiv','post','normal' ); // Talkback Metabox
 remove_meta_box( 'slugdiv','post','normal' ); // Slug Metabox
 remove_meta_box( 'authordiv','post','normal' ); // Author Metabox
 }
   add_action('admin_menu','remove_default_post_screen_metaboxes');


// REMOVE META BOXES FROM DEFAULT PAGES SCREEN
   function remove_default_page_screen_metaboxes() {
 remove_meta_box( 'postcustom','page','normal' ); // Custom Fields Metabox
 remove_meta_box( 'postexcerpt','page','normal' ); // Excerpt Metabox
 remove_meta_box( 'commentstatusdiv','page','normal' ); // Comments Metabox
 remove_meta_box( 'trackbacksdiv','page','normal' ); // Talkback Metabox
 remove_meta_box( 'slugdiv','page','normal' ); // Slug Metabox
 remove_meta_box( 'authordiv','page','normal' ); // Author Metabox
 }
   add_action('admin_menu','remove_default_page_screen_metaboxes');
share|improve this answer
8  
You may have a typo in the above code, shouldn't the second function set the type to page, and not post like the first? –  t31os Nov 26 '10 at 22:24
4  
According to this wordpress.stackexchange.com/questions/34030/… I wouldn't hide the slugdiv this way, but use this gist.github.com/1863830 instead –  Cor van Noorloos Feb 19 '12 at 13:25

Add Custom User Profile Fields

Place the code below into your functions.php file to add custom user profile fields. Edit or add lines as you see fit.

Remember not to remove the line: return $contactmethods; otherwise this won't work.

// CUSTOM USER PROFILE FIELDS
   function my_custom_userfields( $contactmethods ) {

    // ADD CONTACT CUSTOM FIELDS
    $contactmethods['contact_phone_office']     = 'Office Phone';
    $contactmethods['contact_phone_mobile']     = 'Mobile Phone';
    $contactmethods['contact_office_fax']       = 'Office Fax';

    // ADD ADDRESS CUSTOM FIELDS
    $contactmethods['address_line_1']       = 'Address Line 1';
    $contactmethods['address_line_2']       = 'Address Line 2 (optional)';
    $contactmethods['address_city']         = 'City';
    $contactmethods['address_state']        = 'State';
    $contactmethods['address_zipcode']      = 'Zipcode';
    return $contactmethods;
   }
   add_filter('user_contactmethods','my_custom_userfields',10,1);

To display custom fields you can use one of the two methods listed below.

Option 1:

the_author_meta('facebook', $current_author->ID)

Option 2:

<?php $current_author = get_userdata(get_query_var('author')); ?>
<p><a href="<?php echo esc_url($current_author->contact_phone_office);?>" title="office_phone"> Office Phone</a></p>
share|improve this answer

Remove "Wordpress" to "WordPress" filter

Tested on: Wordpress 3.0.1

There was a filter added with WordPress version 3.0 that automatically converts all instances of "Wordpress" (no capital P) to "WordPress" (with a capital P) in post content, post titles, and comment text. Some people see this as intrusive, I just have a need to mis-case WordPress from time to time and found the filter somewhat annoying.

// Remove annoying P filter
if(function_exists('capital_P_dangit')) {
    foreach ( array( 'the_content', 'the_title' ) as $filter ) 
        remove_filter( $filter, 'capital_P_dangit', 11 ); 

    remove_filter('comment_text', 'capital_P_dangit', 31 );
}
share|improve this answer
5  
In WordPress 3.0.1, this filter is added with priority 11, so you need to add 11 as the third parameter to remove it. –  Jan Fabry Nov 5 '10 at 23:01

Customize the order of the admin menu

tested on: Wordpress 3.0.1

This code will allow you to reorganize the order of elements in the admin menu. All that you need to do is click on an existing link in the admin menu and copy everything before the /wp-admin/ URL. The order below represents the order the new admin menu will have.

// CUSTOMIZE ADMIN MENU ORDER
   function custom_menu_order($menu_ord) {
       if (!$menu_ord) return true;
       return array(
        'index.php', // this represents the dashboard link
        'edit.php?post_type=events', // this is a custom post type menu
        'edit.php?post_type=news', 
        'edit.php?post_type=articles', 
        'edit.php?post_type=faqs', 
        'edit.php?post_type=mentors',
        'edit.php?post_type=testimonials',
        'edit.php?post_type=services',
        'edit.php?post_type=page', // this is the default page menu
        'edit.php', // this is the default POST admin menu 
    );
   }
   add_filter('custom_menu_order', 'custom_menu_order');
   add_filter('menu_order', 'custom_menu_order');
share|improve this answer
3  
@kaiser documented here codex.wordpress.org/Plugin_API/Filter_Reference/… –  Manny Fleurmond Aug 18 '12 at 17:08

Customize the Dashboard

add_action('wp_dashboard_setup', 'my_custom_dashboard_widgets');

function my_custom_dashboard_widgets() {
   global $wp_meta_boxes;

Remove these dashboard widgets...

   unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_plugins']);
   unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_primary']);
   unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_secondary']);

Add a custom widget called 'Help and Support'

   wp_add_dashboard_widget('custom_help_widget', 'Help and Support', 'custom_dashboard_help');
}

This is the content for your custom widget

 function custom_dashboard_help() {
    echo '<p>Lorum ipsum delor sit amet et nunc</p>';
}
share|improve this answer

Add Thumbnails in Manage Posts/Pages List

You can add this to your functions to display to the Manage/Edit Post and Pages List a new column with the thumbnail preview.

/****** Add Thumbnails in Manage Posts/Pages List ******/
if ( !function_exists('AddThumbColumn') && function_exists('add_theme_support') ) {

    // for post and page
    add_theme_support('post-thumbnails', array( 'post', 'page' ) );

    function AddThumbColumn($cols) {

        $cols['thumbnail'] = __('Thumbnail');

        return $cols;
    }

    function AddThumbValue($column_name, $post_id) {

            $width = (int) 35;
            $height = (int) 35;

            if ( 'thumbnail' == $column_name ) {
                // thumbnail of WP 2.9
                $thumbnail_id = get_post_meta( $post_id, '_thumbnail_id', true );
                // image from gallery
                $attachments = get_children( array('post_parent' => $post_id, 'post_type' => 'attachment', 'post_mime_type' => 'image') );
                if ($thumbnail_id)
                    $thumb = wp_get_attachment_image( $thumbnail_id, array($width, $height), true );
                elseif ($attachments) {
                    foreach ( $attachments as $attachment_id => $attachment ) {
                        $thumb = wp_get_attachment_image( $attachment_id, array($width, $height), true );
                    }
                }
                    if ( isset($thumb) && $thumb ) {
                        echo $thumb;
                    } else {
                        echo __('None');
                    }
            }
    }

    // for posts
    add_filter( 'manage_posts_columns', 'AddThumbColumn' );
    add_action( 'manage_posts_custom_column', 'AddThumbValue', 10, 2 );

    // for pages
    add_filter( 'manage_pages_columns', 'AddThumbColumn' );
    add_action( 'manage_pages_custom_column', 'AddThumbValue', 10, 2 );
}
share|improve this answer

Function to change the length of Exerpt

Tested on: Wordpress 3.0.1

By default all excerpts are capped at 55 words. Utilizing the code below you can override this default settings:

function new_excerpt_length($length) { 
    return 100;
}

add_filter('excerpt_length', 'new_excerpt_length');

This example changes the excerpt length to 100 words, but you can use the same method to change it to any value.

share|improve this answer
3  
@NetConstructor.com This function (and the excerpt_length hook) cap by words. –  EAMann Sep 15 '10 at 17:53

Auto Extract the First Image from the Post Content

Tested on: Wordpress 3.0.1

This code will automatically extract the first image associated with a post and allow you to display/use it by calling the getImage function.

// AUTOMATICALLY EXTRACT THE FIRST IMAGE FROM THE POST 
function getImage($num) {
    global $more;
    $more = 1;
    $link = get_permalink();
    $content = get_the_content();
    $count = substr_count($content, '<img');
    $start = 0;
    for($i=1;$i<=$count;$i++) {
        $imgBeg = strpos($content, '<img', $start);
        $post = substr($content, $imgBeg);
        $imgEnd = strpos($post, '>');
        $postOutput = substr($post, 0, $imgEnd+1);
        $postOutput = preg_replace('/width="([0-9]*)" height="([0-9]*)"/', '',$postOutput);;
        $image[$i] = $postOutput;
        $start=$imgEnd+1;
    }
    if(stristr($image[$num],'<img')) { echo '<a href="'.$link.'">'.$image[$num]."</a>"; }
    $more = 0;
}
share|improve this answer
6  
Nice, but get_the_image does a very good job with this as well. wordpress.org/extend/plugins/get-the-image –  artlung Sep 15 '10 at 15:56
3  
What does it do differently than the get_the_image script? –  matt Dec 5 '10 at 4:47
1  
@matt -- In wordpress there are different ways that images can be added to posts and i think the get_the_image script just looks at one of those. This checks to see if there is a featured image and uses that one first if available, next I think it checks for the first image added to the post content and if that is not found it checks the media gallery for the image with the highest sort order (at least thats how I remember the order going). –  NetConstructor.com Feb 22 '11 at 20:01

Remove pings to your own blog

Tested on: Wordpress 3.0.1

//remove pings to self
function no_self_ping( &$links ) {
    $home = get_option( 'home' );
    foreach ( $links as $l => $link )
        if ( 0 === strpos( $link, $home ) )
            unset($links[$l]);
}
add_action( 'pre_ping', 'no_self_ping' );
share|improve this answer

Sharpen Resized Images (only jpg)

This function sharpening resized jpg images. An example of difference: http://dl.dropbox.com/u/1652601/forrst/gdsharpen.png

function ajx_sharpen_resized_files( $resized_file ) {

    $image = wp_load_image( $resized_file );
    if ( !is_resource( $image ) )
        return new WP_Error( 'error_loading_image', $image, $file );

    $size = @getimagesize( $resized_file );
    if ( !$size )
        return new WP_Error('invalid_image', __('Could not read image size'), $file);
    list($orig_w, $orig_h, $orig_type) = $size;

    switch ( $orig_type ) {
        case IMAGETYPE_JPEG:
            $matrix = array(
                array(-1, -1, -1),
                array(-1, 16, -1),
                array(-1, -1, -1),
            );

            $divisor = array_sum(array_map('array_sum', $matrix));
            $offset = 0; 
            imageconvolution($image, $matrix, $divisor, $offset);
            imagejpeg($image, $resized_file,apply_filters( 'jpeg_quality', 90, 'edit_image' ));
            break;
        case IMAGETYPE_PNG:
            return $resized_file;
        case IMAGETYPE_GIF:
            return $resized_file;
    }

    return $resized_file;
}   

add_filter('image_make_intermediate_size', 'ajx_sharpen_resized_files',900);
share|improve this answer
1  
Works great for me :) and its so cool! –  Sagive SEO Dec 9 '11 at 13:38
1  
if u guys want this as plugin: wordpress.org/extend/plugins/sharpen-resized-images –  Ünsal Korkmaz Apr 3 '12 at 9:38

Enable GZIP output compression

Normally the server should be set up to do this automatically, but a lot of shared hosts don t do this (probably to increase client bandwidth usage)

 if(extension_loaded("zlib") && (ini_get("output_handler") != "ob_gzhandler"))
   add_action('wp', create_function('', '@ob_end_clean();@ini_set("zlib.output_compression", 1);'));
share|improve this answer

Display DB Queries, Time Spent and Memory Consumption

Tested on: Wordpress 3.0.1

function performance( $visible = false ) {

    $stat = sprintf(  '%d queries in %.3f seconds, using %.2fMB memory',
        get_num_queries(),
        timer_stop( 0, 3 ),
        memory_get_peak_usage() / 1024 / 1024
        );

    echo $visible ? $stat : "<!-- {$stat} -->" ;
}

Then this code below the code above which will automatically insert the code above into the footer of your public website (make sure your theme is calling wp_footer):

add_action( 'wp_footer', 'performance', 20 );

Can be called multiple times.

share|improve this answer

Remove Plugin Update Notice ONLY for INACTIVE plugins

function update_active_plugins($value = '') {
    /*
    The $value array passed in contains the list of plugins with time
    marks when the last time the groups was checked for version match
    The $value->reponse node contains an array of the items that are
    out of date. This response node is use by the 'Plugins' menu
    for example to indicate there are updates. Also on the actual
    plugins listing to provide the yellow box below a given plugin
    to indicate action is needed by the user.
    */
    if ((isset($value->response)) && (count($value->response))) {

        // Get the list cut current active plugins
        $active_plugins = get_option('active_plugins');    
        if ($active_plugins) {

            //  Here we start to compare the $value->response
            //  items checking each against the active plugins list.
            foreach($value->response as $plugin_idx => $plugin_item) {

                // If the response item is not an active plugin then remove it.
                // This will prevent WordPress from indicating the plugin needs update actions.
                if (!in_array($plugin_idx, $active_plugins))
                    unset($value->response[$plugin_idx]);
            }
        }
        else {
             // If no active plugins then ignore the inactive out of date ones.
            foreach($value->response as $plugin_idx => $plugin_item) {
                unset($value->response);
            }          
        }
    }  
    return $value;
}
add_filter('transient_update_plugins', 'update_active_plugins');    // Hook for 2.8.+
//add_filter( 'option_update_plugins', 'update_active_plugins');    // Hook for 2.7.x
share|improve this answer

Unregister WP Default Widgets

Tested on: Wordpress 3.0.1

// unregister all default WP Widgets
function unregister_default_wp_widgets() {
    unregister_widget('WP_Widget_Pages');
    unregister_widget('WP_Widget_Calendar');
    unregister_widget('WP_Widget_Archives');
    unregister_widget('WP_Widget_Links');
    unregister_widget('WP_Widget_Meta');
    unregister_widget('WP_Widget_Search');
    unregister_widget('WP_Widget_Text');
    unregister_widget('WP_Widget_Categories');
    unregister_widget('WP_Widget_Recent_Posts');
    unregister_widget('WP_Widget_Recent_Comments');
    unregister_widget('WP_Widget_RSS');
    unregister_widget('WP_Widget_Tag_Cloud');
}
add_action('widgets_init', 'unregister_default_wp_widgets', 1);
share|improve this answer

Output which theme template file a post/page is using in the header

add_action('wp_head', 'show_template');
function show_template() {
    global $template;
    print_r($template);
}

Shorten the default DIV output if your theme is using post_class.

if your theme is using something like

<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

You can have crazy long divs in your source that might look like this or even longer:

<div id="post-4" class="post-4 post type-post hentry category-uncategorized category-test category-test-1-billion category-test2 category-test3 category-testing"> 

This can really start to clutter your source and seem rather unnecessary in most cases, going 3-4 deep is good enough.

For the top example we can slice the output like so:

// slice crazy long div outputs
    function category_id_class($classes) {
        global $post;
        foreach((get_the_category($post->ID)) as $category)
            $classes[] = $category->category_nicename;
            return array_slice($classes, 0,5);
    }
    add_filter('post_class', 'category_id_class');

this slices the output to only include the first 5 values, so the above example becomes:

<div id="post-4" class="post-4 post type-post hentry category-uncategorized"> 

Make category archives display all posts, regardless of post type: good for custom post types

function any_ptype_on_cat($request) {
 if ( isset($request['category_name']) )
  $request['post_type'] = 'any';

 return $request;
}
add_filter('request', 'any_ptype_on_cat');

Remove unwanted dashboard items

This was already posted but it did not have the full list of items. Especially those annoying "incoming links!"

add_action('wp_dashboard_setup', 'my_custom_dashboard_widgets');

function my_custom_dashboard_widgets() {
global $wp_meta_boxes;
 //Right Now - Comments, Posts, Pages at a glance
unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_right_now']);
//Recent Comments
unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_recent_comments']);
//Incoming Links
unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_incoming_links']);
//Plugins - Popular, New and Recently updated Wordpress Plugins
unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_plugins']);

//Wordpress Development Blog Feed
unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_primary']);
//Other Wordpress News Feed
unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_secondary']);
//Quick Press Form
unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_quick_press']);
//Recent Drafts List
unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_recent_drafts']);
}

Remove "Read More" page jumps**

instead return to the top of the page. You know how when you click "read more" it will jump to the spot in the page which can be annoying, this makes it just load the page normally, no jumping!

function remove_more_jump_link($link) { 
$offset = strpos($link, '#more-');
if ($offset) {
$end = strpos($link, '"',$offset);
}
if ($end) {
$link = substr_replace($link, '', $offset, $end-$offset);
}
return $link;
}
add_filter('the_content_more_link', 'remove_more_jump_link');

Restrict ADMIN menu items based on username, replace username with an actual user's name.

function remove_menus()
{
    global $menu;
    global $current_user;
    get_currentuserinfo();

    if($current_user->user_login == 'username')
    {
        $restricted = array(__('Posts'),
                            __('Media'),
                            __('Links'),
                            __('Pages'),
                            __('Comments'),
                            __('Appearance'),
                            __('Plugins'),
                            __('Users'),
                            __('Tools'),
                            __('Settings')
        );
        end ($menu);
        while (prev($menu)){
            $value = explode(' ',$menu[key($menu)][0]);
            if(in_array($value[0] != NULL?$value[0]:"" , $restricted)){unset($menu[key($menu)]);}
        }// end while

    }// end if
}
add_action('admin_menu', 'remove_menus');

//alternatively you can use if($current_user->user_login != 'admin') instead, probably more useful

Style the tag cloud

//tag cloud custom
add_filter('widget_tag_cloud_args','style_tags');
function style_tags($args) {
$args = array(
     'largest'    => '10',
     'smallest'   => '10',
     'format'     => 'list',
     );
return $args;
}

Full reference of options here ( there are a lot!) http://codex.wordpress.org/Function_Reference/wp_tag_cloud

Change Default RSS Widget update timer

( default is 6 or 12 hours I forget (1800 =30min).

add_filter( 'wp_feed_cache_transient_lifetime', create_function('$fixrss', 'return 1800;') );
share|improve this answer

Remove superfluous info and HTML within the <head> tag

// remove unnecessary header info
function remove_header_info() {
    remove_action('wp_head', 'rsd_link');
    remove_action('wp_head', 'wlwmanifest_link');
    remove_action('wp_head', 'wp_generator');
    remove_action('wp_head', 'start_post_rel_link');
    remove_action('wp_head', 'index_rel_link');
    remove_action('wp_head', 'adjacent_posts_rel_link');         // for WordPress <  3.0
    remove_action('wp_head', 'adjacent_posts_rel_link_wp_head'); // for WordPress >= 3.0
}
add_action('init', 'remove_header_info');

// remove extra CSS that 'Recent Comments' widget injects
function remove_recent_comments_style() {
    global $wp_widget_factory;
    remove_action('wp_head', array(
        $wp_widget_factory->widgets['WP_Widget_Recent_Comments'],
        'recent_comments_style'
    ));
}
add_action('widgets_init', 'remove_recent_comments_style');
share|improve this answer

Automatically Add Dynamic Titles to Public Pages

Tested on: Wordpress 3.0.1

Utilizing the code below will automatically create dynamic page titles based upon the pages/posts being viewed publicly.

/* Dynamic Titles **/
// This sets your <title> depending on what page you're on, for better formatting and for SEO
// You need to set the variable $longd to some custom text at the beginning of the function
function dynamictitles() {
$longd = __('Enter your longdescription here.', 'texdomainstring');
    if ( is_single() ) {
      wp_title('');
      echo ' | '.get_bloginfo('name');

} else if ( is_page() || is_paged() ) {
      bloginfo('name');
      wp_title('|');

} else if ( is_author() ) {
      bloginfo('name');
      wp_title(' | '.__('Author', 'texdomainstring'));

} else if ( is_category() ) {
      bloginfo('name');
      wp_title(' | '.__('Archive for', 'texdomainstring'));

} else if ( is_tag() ) {
      echo get_bloginfo('name').' | '.__('Tag archive for', 'texdomainstring');
      wp_title('');

} else if ( is_archive() ) {
      echo get_bloginfo('name').' | '.__('Archive for', 'texdomainstring');
      wp_title('');

} else if ( is_search() ) {
      echo get_bloginfo('name').' | '.__('Search Results', 'texdomainstring');
} else if ( is_404() ) {
      echo get_bloginfo('name').' | '.__('404 Error (Page Not Found)', 'texdomainstring');

} else if ( is_home() ) {
      echo get_bloginfo('name').' | '.get_bloginfo('description');

} else {
      echo get_bloginfo('name').' | '.($blog_longd);
}
}
share|improve this answer

Wordpress Custom Admin Footer

// customize admin footer text
function custom_admin_footer() {
        echo 'add your custom footer text and html here';
} 
add_filter('admin_footer_text', 'custom_admin_footer');

I use this for client sites as a simple point of reference to contact me as the dev.

share|improve this answer

New Roles and Capabilities - Only run once!

I keep these handy, this is the right way to do them without a plugin. They set a single field (prefix_user_roles) in the options database, and you don't need a plugin to set them. Refer to the Codex page for a list of what capabilities are available and descriptions for what they do. You only need to uncomment one of these blocks, load any page and then comment them again! Here I'm creating a role that's got the capabilities I need:

/* Capabilities */

// To add the new role, using 'international' as the short name and
// 'International Blogger' as the displayed name in the User list and edit page:
/*
add_role('international', 'International Blogger', array(
    'read' => true, // True allows that capability, False specifically removes it.
    'edit_posts' => true,
    'delete_posts' => true,
    'edit_published_posts' => true,
    'publish_posts' => true,
    'edit_files' => true,
    'import' => true,
    'upload_files' => true //last in array needs no comma!
));
*/


// To remove one outright or remove one of the defaults:
/* 
remove_role('international');
*/

It's sometimes handy to add/remove from an existing role rather than removing and re-adding one. Again, you only need to uncomment it, reload a page and then comment it again. This will store the role/capability properly in the options table. (This allows you, the developer to control them and removes the overhead of the bulky plugins that do the same thing.) Here I'm changing the author role to delete their published posts (the default), but allowing them the capability to edit their published posts (which isn't possible for this role by default)-- using *add_cap* or *remove_cap*.

/*
$edit_role = get_role('author');
   $edit_role->add_cap('edit_published_posts');
   $edit_role->remove_cap('delete_published_posts');
*/

I keep a spreadsheet with the grid from the Codex page for sites that modify this way, so I can remember how things are set, though leaving the commented out code in your functions.php file will work to. Don't leave these examples uncommented, or it will write to the database with each page load!

share|improve this answer
1  
@tomcat23 - Water under the bridge at this point. All I'm saying is, I'm not interested in placing blame, just in having peace for everyone moving forward. :) –  MikeSchinkel Mar 13 '11 at 6:55
2  
@MikeSchinkel Yes, you are right. @kaiser My apologies if I've caused you insult. –  tomcat23 Mar 13 '11 at 8:08
1  
@MikeSchinkel: thanks for bringing peace back in. @tomcat23: No, you didn't. I can deal with that sort of criticism. My apologies too. –  kaiser Mar 13 '11 at 17:44

Enable Error Debugging And Logging To Use On Live Sites

This is a piece of code I wrote to make use of the WP_DEBUG constants that are normally disabled by default. Well I created a way to not only enable WP_DEBUG so you can use it on a live site with no negative side-effects, but I also made use of the other debugging constants for forcing errors to be displayed, and for creating a log file of the errors and Notices in the /wp-content directory.

Drop this code in your wp-config.php file ( AFTER YOU SAVE A BACKUP JUST IN CASE ) and then you can pass the ?debug=1, 2, or 3 parameters at the end of any url on your site.

?debug=1 = shows all errors/notices ?debug=2 = forces them to be displayed ?debug=3 = creates a debug.log file of all errors in /wp-content dir.

/**
* Written by Jared Williams - http://new2wp.com
* @wp-config.php replace WP_DEBUG constant with this code
* Enable WP debugging for usage on a live site
* http://core.trac.wordpress.org/browser/trunk/wp-includes/load.php#L230
* Pass the '?debug=#' parameter at the end of any url on site
*
* http://example.com/?debug=1, /?debug=2, /?debug=3
*/
if ( isset($_GET['debug']) && $_GET['debug'] == '1' ) {
    // enable the reporting of notices during development - E_ALL
    define('WP_DEBUG', true);
} elseif ( isset($_GET['debug']) && $_GET['debug'] == '2' ) {
    // must be true for WP_DEBUG_DISPLAY to work
    define('WP_DEBUG', true);
    // force the display of errors
    define('WP_DEBUG_DISPLAY', true);
} elseif ( isset($_GET['debug']) && $_GET['debug'] == '3' ) {
    // must be true for WP_DEBUG_LOG to work
    define('WP_DEBUG', true);
    // log errors to debug.log in the wp-content directory
    define('WP_DEBUG_LOG', true);
}

I go into more detail on the guest post I wrote for Comluv if you're interested, here: http://comluv.com/dev/enable-debugging-and-logging-for-live-site-usage/

I'm still working on a way to make this either password protected, or preferrably somehow make it work on if (current_user_can('manage_themes') and is_logged_in().

But that's where it gets alot more tricky.

share|improve this answer

Enable shortcodes in widgets

// shortcode in widgets
if ( !is_admin() ){
    add_filter('widget_text', 'do_shortcode', 11);
}
share|improve this answer

Function to Disable RSS Feeds

Tested on: Wordpress 3.0.1

You can disable RSS feeds If you want to maintain your Wordpress based website as static.

You can Use this function :

function fb_disable_feed() {
wp_die( __('No feed available,please visit our <a href="'. get_bloginfo('url') .'">homepage</a>!') );
}

add_action('do_feed', 'fb_disable_feed', 1);
add_action('do_feed_rdf', 'fb_disable_feed', 1);
add_action('do_feed_rss', 'fb_disable_feed', 1);
add_action('do_feed_rss2', 'fb_disable_feed', 1);
add_action('do_feed_atom', 'fb_disable_feed', 1);
share|improve this answer

Include custom post types in "Right Now" admin dashboard

This will include your custom post types and the post counts for each type in the "Right Now" dashboard widget.

// ADD CUSTOM POST TYPES TO THE 'RIGHT NOW' DASHBOARD WIDGET
function wph_right_now_content_table_end() {
 $args = array(
  'public' => true ,
  'show_ui' => true ,
  '_builtin' => false
 );
 $output = 'object';
 $operator = 'and';

 $post_types = get_post_types( $args , $output , $operator );
 foreach( $post_types as $post_type ) {
  $num_posts = wp_count_posts( $post_type->name );
  $num = number_format_i18n( $num_posts->publish );
  $text = _n( $post_type->labels->singular_name, $post_type->labels->name , intval( $num_posts->publish ) );
  if ( current_user_can( 'edit_posts' ) ) {
   $num = "<a href='edit.php?post_type=$post_type->name'>$num</a>";
   $text = "<a href='edit.php?post_type=$post_type->name'>$text</a>";
  }
  echo '<tr><td class="first b b-' . $post_type->name . '">' . $num . '</td>';
  echo '<td class="t ' . $post_type->name . '">' . $text . '</td></tr>';
 }
 $taxonomies = get_taxonomies( $args , $output , $operator ); 
 foreach( $taxonomies as $taxonomy ) {
  $num_terms  = wp_count_terms( $taxonomy->name );
  $num = number_format_i18n( $num_terms );
  $text = _n( $taxonomy->labels->singular_name, $taxonomy->labels->name , intval( $num_terms ));
  if ( current_user_can( 'manage_categories' ) ) {
   $num = "<a href='edit-tags.php?taxonomy=$taxonomy->name'>$num</a>";
   $text = "<a href='edit-tags.php?taxonomy=$taxonomy->name'>$text</a>";
  }
  echo '<tr><td class="first b b-' . $taxonomy->name . '">' . $num . '</td>';
  echo '<td class="t ' . $taxonomy->name . '">' . $text . '</td></tr>';
 }
}
add_action( 'right_now_content_table_end' , 'wph_right_now_content_table_end' );
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.