plugins - Best collection of code for your 'functions.php' file

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by fac

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. Closed 13 years ago.

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.

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. Closed 13 years ago.

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.

Share Improve this question edited Feb 4, 2020 at 22:50 community wiki
17 revs, 5 users 57%
NetConstructor 25
  • 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 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 Discuss it on Meta where people can see your arguments better. :) – fuxia Commented Feb 24, 2012 at 17:10
 |  Show 20 more comments

108 Answers 108

Reset to default 1 2 3 4 Next 110

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.

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

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.

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

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

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

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.

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

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

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

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

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

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>

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.

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.

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

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

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

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

It can be called multiple times.

Unregister WordPress Default Widgets

Tested on: WordPress 3.0.1

// Unregister all default WordPress 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);

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

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

A full reference of options are here (there are a lot!) http://codex.wordpress/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;') );

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

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(
        $wp_widget_factory->widgets['WP_Widget_Recent_Comments'],
        'recent_comments_style'
    ) );
}

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
* @wp-config.php replace WP_DEBUG constant with this code
* Enable WP debugging for usage on a live site
* http://core.trac.wordpress/browser/trunk/wp-includes/load.php#L230
* Pass the '?debug=#' parameter at the end of any URL on site
*
* http://example/?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/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.

Enable shortcodes in widgets

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

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!

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

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.

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() {
    wp_enqueue_script('jquery');
}
// Modify
function artdev_nohowdy_f() {
global $nohowdy;
echo <<<JS
<script type="text/javascript">
//<![CDATA[
var nohowdy = "$nohowdy";
jQuery('#user_info p')
    .html(
    jQuery('#user_info p')
        .html()
        .replace(/Howdy/,nohowdy)
    );
//]]>
JS;
}

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744777909a4593154.html

相关推荐

  • plugins - Best collection of code for your &#39;functions.php&#39; file

    As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by fac

    19小时前
    260

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信