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.

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.

  • 13
    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
    Commented Sep 9, 2010 at 14:43
  • 17
    All answers not related to a theme should be removed. This thread is a good example for bad coding practices.
    – fuxia
    Commented Jun 13, 2011 at 12:09
  • 17
    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
    Commented Jan 16, 2012 at 18:49
  • 3
    @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.
    – fuxia
    Commented Feb 22, 2012 at 2:44
  • 6
    @NetConstructor.com Discuss it on Meta where people can see your arguments better. :)
    – fuxia
    Commented Feb 24, 2012 at 17:10

108 Answers 108


Enable Hidden Administration 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 administrator user and hide it for all other users.

   function all_settings_link() {
    add_options_page(__('All Settings'), __('All Settings'), 'administrator', 'options.php');
   add_action('admin_menu', 'all_settings_link');
  • Fantastic for development! I use the options table frequently to store DB versions for my plug-ins ... using phpMyAdmin to reset to an old DB version to test an upgrade script is a pain ... this will make it so much easier!!!
    – EAMann
    Commented Sep 15, 2010 at 16:03
  • 3
    You can also get to the same options page (when logged in) by going to yoursite/wp-admin/options.php
    – j08691
    Commented Oct 9, 2015 at 19:55

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;

Include custom post types in the search results.

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.

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.

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' );
  • Regarding the last snippet to this answer. This is a great addition as I was adding these manually for each post type. The only issue I have with this is that it adds the data after the default "category" and "tag" entry. Could you update your answer to move the default "category" or "tag" ones down or remove them so that they can be added manually? Commented Feb 22, 2011 at 20:06
  • @NetConstructor.com I don't think I understand your request. If I do, then I think it would be a bit more of a difficult thing to do, and don't really have time right now to figure out how to do it.
    – jaredwilli
    Commented Feb 23, 2011 at 1:01
  • Include custom post types in the search results - I guess, now you can do this with exclude_from_search param of register_post_type... Commented Dec 16, 2013 at 16:13

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

   global $user_login;
   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'):

       global $user_login;
       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;" ) );
  • 8
    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.
    – jerclarke
    Commented Sep 11, 2010 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)
    – jerclarke
    Commented Sep 11, 2010 at 20:29
  • Thats why I added the comment to the code where you can change the admin username. How would you improve/rewrite it? Commented Sep 12, 2010 at 9:07
  • The best way is to remove the global $user_login and get_currentuserinfo() and instead use current_user_can in your if clause. It's only 1 line instead of 3 and its the standard way. You can check for the specific capability that would be needed to ACT on the messages, in this case there's 'update_core' and 'update_plugins'.
    – jerclarke
    Commented Sep 12, 2010 at 14:00
  • 2
    so: if (!current_user_can('update_plugins')) {/*REMOVE MESSAGES*/}
    – jerclarke
    Commented Sep 12, 2010 at 14:01

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 WordPress 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 syntax to default $where
        $where .= " AND TIMESTAMPDIFF($device, $wpdb->posts.post_date_gmt, '$now') > $wait ";
    return $where;
add_filter('posts_where', 'publish_later_on_feed');
  • source on my post: wpengineer.com/320/publish-the-feed-later with more informations
    – bueltge
    Commented Sep 17, 2010 at 8:29
  • 1
    You can also just remove the generator filter: remove_action('wp_head', 'wp_generator');
    – Gipetto
    Commented Sep 18, 2010 at 7:01
  • 26
    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.
    – fuxia
    Commented Nov 10, 2010 at 14:41
  • 6
    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. Commented Feb 11, 2011 at 6:38
  • 1
    Not true Joseph, if your WordPress version is exposed then people can see if you are running an older version, thus exposing your vulnerabilities. It is always a good decision to remove that from all WordPress installs. Personally, I don't even know why they put it there in the first place as it IS a security issue.
    – Jeremy
    Commented May 12, 2014 at 15:51

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

Tested on: WordPress 3.0.1

The default is infinite, and this will set it to only remember the last five edits:

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

For what it's worth, there are a ton of great ideas for CONSTANTS that can be set on the Codex page Editing wp-config.php.

  • Can this be set on a per post type basis? Commented Sep 12, 2010 at 9:17
  • Looking at its usage in wp_save_post_revision() there doesn't seem to be a way to distinguish based on post types. There's no filter or anything on the value, though there probably should be.
    – jerclarke
    Commented Sep 12, 2010 at 14:24
  • thanks Jeremy - To anyone else, if you know how to do this please post it here. Commented Sep 14, 2010 at 7:18
  • 1
    personally I prefer 10. I know it's double but always when I need a revision it's always older then 5
    – janw
    Commented Sep 4, 2012 at 12:04

WordPress Profiling tools

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

    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 {
            echo '</pre>' . "\n";
            return $in;
        } # dump()

     * 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 {
        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' )

        if ( $_GET['debug'] == 'cron' ) {
            $crons = get_option('cron');

            foreach ( $crons as $time => $_crons ) {

                if ( !is_array($_crons) )

                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']);
                            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' ) {
    } # 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 )
                '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);
  • is there a quick way to modify this so that script only gets called when your an administrator AND append something to the URL to show the debug info? Commented Feb 22, 2011 at 19:58
  • 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). Commented Feb 23, 2011 at 9:50

Sharpen Resized Images (only JPEG)

This function sharpens resized JPEG images. An example of a difference:


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

        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);
  • much much better jpegs, thanks a bunch! tested in 3.4-alpha
    – brasofilo
    Commented Apr 2, 2012 at 12:07
  • 2
    if u guys want this as plugin: wordpress.org/extend/plugins/sharpen-resized-images Commented Apr 3, 2012 at 9:38
  • where does this function go?
    – StevieD
    Commented Mar 18, 2019 at 2:04
  • @StevieD - as the title suggests, it goes inside functions.php, in your template. I would be careful though, this function is almost 8 years old. Commented Jul 25, 2019 at 7:54

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.

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

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

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, but 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 );
  • great little find. One of those things which just removes another piece of code that is not needed Commented Sep 17, 2010 at 6:50
  • 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
    Commented Nov 5, 2010 at 23:01

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


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>';

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.

   function my_custom_userfields( $contactmethods ) {

    $contactmethods['contact_phone_office']     = 'Office Phone';
    $contactmethods['contact_phone_mobile']     = 'Mobile Phone';
    $contactmethods['contact_office_fax']       = 'Office Fax';

    $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;

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>

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.

  • @user402... does this cap by words or characters? Could you post how to do both? Commented Sep 12, 2010 at 9:14
  • 3
    @NetConstructor.com This function (and the excerpt_length hook) cap by words.
    – EAMann
    Commented Sep 15, 2010 at 17:53
  • Heh. I got that filter added to core. :) Commented Mar 8, 2011 at 19:22

Customize the order of the administration menu

Tested on: WordPress 3.0.1

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

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=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');

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 );
  • How to move the column to the far left?
    – 730wavy
    Commented Oct 8, 2013 at 17:10

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 ) )
add_action( 'pre_ping', 'no_self_ping' );
  • how often and when does wordpress ping itself? Commented Sep 17, 2010 at 6:54
  • I actually have that issue quite often. If I reference an internal link to another post on my WP blog, I get a trackback or pingback (don't remember which) from myself. It's annoying. Commented Dec 18, 2010 at 23:12
  • Same here. I have a news / magazine blog and link to other articles quite often.
    – Steven
    Commented Feb 13, 2011 at 13:24

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

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',
            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 );

It can be called multiple times.

  • for php < 5.2 use memory_get_usage() Commented Jan 23, 2011 at 8:23

Unregister WordPress Default Widgets

Tested on: WordPress 3.0.1

// Unregister all default WordPress Widgets
function unregister_default_wp_widgets() {
add_action('widgets_init', 'unregister_default_wp_widgets', 1);
  • I have used it on Version 3.1.4 . But the widgets are still there. Does any one have idea?
    – user391
    Commented Jul 1, 2011 at 14:22
  • Still works on WP 4.5 :)
    – Tim Malone
    Commented Apr 19, 2016 at 3:26

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.

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;

    if(stristr($image[$num],'<img')) {
        echo '<a href="'.$link.'">'.$image[$num]."</a>";
    $more = 0;
  • 6
    Nice, but get_the_image does a very good job with this as well. wordpress.org/extend/plugins/get-the-image
    – artlung
    Commented Sep 15, 2010 at 15:56
  • correct but this one works differently and fixes various issues which get_the_image does not take into account Commented Sep 30, 2010 at 11:19
  • 4
    What does it do differently than the get_the_image script?
    – matt
    Commented Dec 5, 2010 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). Commented Feb 22, 2011 at 20:01
  • i suggest wordpress.org/extend/plugins/auto-post-thumbnail Automatically generate the Post Thumbnail (Featured Thumbnail) from the first image in post or any custom post type only if Post Thumbnail is not set Commented May 8, 2011 at 12:47

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

add_action('wp_head', 'show_template');
function show_template() {
    global $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

    // Recent Comments

    // Incoming Links

    // Plugins - Popular, New and Recently updated Wordpress Plugins

    // WordPress Development Blog Feed

    // Other WordPress News Feed

    // Quick Press Form

    // Recent Drafts List

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;

    if($current_user->user_login == 'username')
        $restricted = array(__('Posts'),
        end ($menu);
        while (prev($menu)) {
            $value = explode(' ',$menu[key($menu)][0]);
            if(in_array($value[0] != NULL ? $value[0] : "" , $restricted)) {
        } // 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;

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

Change Default RSS Widget update timer

(The default is 6 or 12 hours - I forget (1800 = 30 minutes).

add_filter( 'wp_feed_cache_transient_lifetime', create_function('$fixrss', 'return 1800;') );
  • could you please split up each of these into seperate answers within the next few weeks. I was going to do it for you but did not want to make it seem like I am taking credit for your answers. In any case - I am trying to keep this organized so users can easily find the information they are looking for. Thanks in advance Commented Jan 26, 2011 at 14:25
  • I was just using the code "Restrict ADMIN menu items based on username, replace username with an actual user's name" which is great but could you update the code to also show how this can be done for a specific "user role". I think this would be very useful! Commented Feb 22, 2011 at 20:13
  • Sorry NetConstructor I just saw your comment now. For user role I would use "current_user_can". I don't have time to test it but when I do, I will add it.
    – Wyck
    Commented Mar 4, 2011 at 3:47
  • default value for wp_feed_cache_transient_lifetime is 43200 (12 hours)
    – brasofilo
    Commented Apr 2, 2012 at 22:15

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))
        else {
             // If no active plugins then ignore the inactive out of date ones.
            foreach($value->response as $plugin_idx => $plugin_item) {
    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
  • 2
    This is not necessarily a good idea - an inactive plugin is still present in the filesystem, and an insecure one can still be utilised to hack the site. Plugins should always be kept up-to-date.
    – Tim Malone
    Commented Apr 11, 2016 at 20:45

Remove superfluous info and HTML within the <head> tag

// remove unnecessary header info
add_action( 'init', 'remove_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

// remove extra CSS that 'Recent Comments' widget injects
add_action( 'widgets_init', 'remove_recent_comments_style' );
function remove_recent_comments_style() {
    global $wp_widget_factory;
    remove_action( 'wp_head', array(
    ) );

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.

  • We use something similar to setup live, staging and dev database connection details.
    – Tom
    Commented Mar 7, 2011 at 17:14

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:

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

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!

  • The functions I mention above write to a field in the options database. Commenting and uncommenting them is the way to go. There are plugins for user roles, but if you use the functions mention above, you cannot leave these functions running, and you DO NOT need to set them more than once, or set them based on if a specific user is accessing something. If you want that, set that user up with a specific, unique role. And refer to the codex, everything I write above is 100% correct if you do it without a plugin. For nearly every case, you only need to set the user roles once.
    – tomcat23
    Commented Feb 2, 2011 at 8:58
  • @tomcat23: To illustrate, i wrapped it up in a function to only add the role, when it doesn't already exists. Another note: I guess it would be easier to place the role somewhere in the role hierarchy, with retrieving the caps from some built in role and then add/remove the capabilities from the built in role. Would make it more clear and easier to remember if it's caps are placed somewhere between ex. admin and editor. - I hope you don't mind that i edited your answer. If you do, pls role it back. :)
    – kaiser
    Commented Mar 1, 2011 at 16:25
  • 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. :) Commented Mar 13, 2011 at 6:55
  • 2
    @MikeSchinkel Yes, you are right. @kaiser My apologies if I've caused you insult.
    – tomcat23
    Commented Mar 13, 2011 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
    Commented Mar 13, 2011 at 17:44

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() ) {
          echo ' | '.get_bloginfo('name');

    } else if ( is_page() || is_paged() ) {

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

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

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

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

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

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.


Enable shortcodes in widgets

// shortcode in widgets
if ( !is_admin() ){
    add_filter('widget_text', 'do_shortcode', 11);

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

Change the "Howdy" message to "Welcome"

With this function you can customize the "Howdy" message in top right of your admin area.
This function make use of JQuery to change the "Howdy" message to "Welcome".

/****** Customize admin message "Howdy" to "Welcome" ******/
$nohowdy = "Welcome";

if (is_admin()) {
    add_action('init', 'artdev_nohowdy_h');
    add_action('admin_footer', 'artdev_nohowdy_f');
// Load jQuery
function artdev_nohowdy_h() {
// Modify
function artdev_nohowdy_f() {
global $nohowdy;
echo <<<JS
<script type="text/javascript">
var nohowdy = "$nohowdy";
jQuery('#user_info p')
    jQuery('#user_info p')

PHP version, using gettext filter:

add_filter('gettext', 'change_howdy', 10, 3);

function change_howdy($translated, $text, $domain) {

    if (!is_admin() || 'default' != $domain)
        return $translated;

    if (false !== strpos($translated, 'Howdy'))
        return str_replace('Howdy', 'Welcome', $translated);

    return $translated;
  • 3
    Can't this already be edited on the PHP side so it doesn't get output at all?
    – hakre
    Commented Feb 14, 2011 at 19:13
  • It's working fine here in 3.0+ versions for sure, but why not in older versions? Check if any other plugin you use is responsible for this. The text here replaced with JQuery, maybe a JQuery plugin?
    – Philip
    Commented Feb 14, 2011 at 20:25

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