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

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

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

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

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

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

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

share|improve this question

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

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

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

108 Answers 108

Remove default fields contact info user profile and replace them with something more usable

The second part of this function has already been mentioned above, but removing the default fields - AIM, Yahoo IM and Jabber/Google Talk - not yet:

function update_contact_methods( $contactmethods ) {

// Remove annoying and unwanted default fields  
unset($contactmethods['aim']);  
unset($contactmethods['jabber']);  
unset($contactmethods['yim']);  

// Add new fields  
$contactmethods['phone'] = 'Phone';  
$contactmethods['mobile'] = 'Mobile';  
$contactmethods['address'] = 'Address';  

return $contactmethods;
}
add_filter('user_contactmethods', 'update_contact_methods');

Of course you can add as many fields as you want (see previous examples earlier in this thread) under "Add new fields"

share|improve this answer

Make your Shortlinks Shorter by Removing WWW

Tested on: Wordpress 3.0.1

Make your shortlinks shorter if you include www. in your domain. Via scratch99.com:

add_filter('get_shortlink','sjc_alter_shortlink');
function sjc_alter_shortlink($shortlink) {
    $shortlink = preg_replace('/^(https?:\/\/)?(www\.)/','$1',$shortlink);
    return $shortlink;
}
share|improve this answer
1  
A check should be added to make sure the string "www." is only removed if it is found at the very beginning of the domain part of the original URL. Naively replacing it anywhere in the URL will lead to bugs if it had been used on a domain like owww.com (which actually appears to be running WordPress) :) –  Ingve May 28 '12 at 21:30

Themed custom loop using shortcodes

Arguments are the same as the ones from query_posts. The content wrapped between the query tag is the template.

add_shortcode('query', 'shortcode_query');

function shortcode_query($atts, $content){
  extract(shortcode_atts(array( // a few default values
   'posts_per_page' => '10',
   'caller_get_posts' => 1,
   'post__not_in' => get_option('sticky_posts'),
  ), $atts));

  global $post;

  $posts = new WP_Query($atts);
  $output = '';
  if ($posts->have_posts())
    while ($posts->have_posts()):
      $posts->the_post();

      // these arguments will be available from inside $content
      $parameters = array(
        'PERMALINK' => get_permalink(),
        'TITLE' => get_the_title(),
        'CONTENT' => get_the_content(),
        'COMMENT_COUNT' => $post->comment_count,
        'CATEGORIES' => get_the_category_list(', '),
        // add here more...
      );

      $finds = $replaces = array();
      foreach($parameters as $find => $replace):
        $finds[] = '{'.$find.'}';
        $replaces[] = $replace;
      endforeach;
      $output .= str_replace($finds, $replaces, $content);

    endwhile;
  else
    return; // no posts found

  wp_reset_query();
  return html_entity_decode($output);
}

Usage:

[query post_type=page posts_per_page=5]
Listing some pages:    
<h5>{TITLE}</h5>
<div>{CONTENT}</div>
<p><a href="{PERMALINK}">{COMMENT_COUNT} comments</a></p>
[/query]

(will make a query for 5 pages)


Inserting pre-configured widgets anywhere using shortcodes

(some ideas from http://webdesign.anmari.com/shortcode-any-widget)

add_action('widgets_init', 'create_arbitrary_sidebar');
function create_arbitrary_sidebar(){
  register_sidebar(array(
    'name' => __('Arbitrary Widgets'),
    'id' => 'arbitrary',
    'description' => sprintf(__('Widgets from this area can added into posts/pages using the %1$s or %2$s shortcodes.'), '[widget ID]', '[widget Name]'),
    'before_widget' => '<div class="block"><div class="block-content block-%2$s clear-block" id="instance-%1$s">',
    'after_widget' => '</div></div>',
    'before_title' => '<h3 class="title">',
    'after_title' => '</h3>'
   ));
}

add_action('in_widget_form', 'widget_shortcodes_info', 10, 3);
function widget_shortcodes_info($widget, $return, $instance){
  if(!is_numeric($widget->number)) return; // wp-save bug :( widget needs to be saved first...

  global $wp_registered_widgets;

  // get the active widgets from all sidebars
  $sidebars_widgets = wp_get_sidebars_widgets();

  // prepare matches
  $matches = array();
  foreach($wp_registered_widgets as $i => $w)
    if($w['name'] == $widget->name) $matches[] = $w['id'];

  // find out the widget position (number)
  $number = 0;
  $is_arbitrary = false;
  if(!empty($sidebars_widgets['arbitrary']))
    foreach($sidebars_widgets['arbitrary'] as $i => $value):
      if(in_array($value, $matches) && !$is_arbitrary) $number = $number +1;
      if($value == $widget->id) $is_arbitrary = true;
    endforeach;

  echo '<div style="background:#eee; padding: 5px;">To include this widget into your posts or pages use one of the following shortcodes: <br />';
  echo '<code>[widget '.substr(md5($widget->id), 0, 8).']</code> <br /> <code>[widget "'.$widget->name.'"'.(($number > 1) ? ' number='.$number : null).']</code></div>';
}

add_shortcode('widget', 'shortcode_widget');
function shortcode_widget($atts){
  global $wp_registered_widgets, $wp_registered_sidebars;
  extract(shortcode_atts(array(
    'number' => false,        // only taken in consideration if the 1st argument is the "Widget Name" (not the hashed ID)
    'title' => true,          // show titles?
    'area' => 'arbitrary'     // sidebar to search
  ), $atts));

  // get 1st parameter (assuming this is the target widget id or name)
  if (!empty($atts[0])) $widget = esc_attr($atts[0]); else return;

  $sidebar = esc_attr($area);
  $number = intval($number);

  $callback = false;
  $possible_matches = array();
  $sidebars_widgets = wp_get_sidebars_widgets();
  if((empty($sidebars_widgets[$sidebar]) || empty($wp_registered_widgets)) && (current_user_can('edit_themes')))
    return "no valid active widgets in {$sidebar}";

  // assuming we get the md5 hashed ID
  foreach ($wp_registered_widgets as $i => $w)
    if ($widget == substr(md5($w['id']), 0, 8)):
      $callback = ($w['callback']);
      $widget = $w['id']; // real widget ID

    // compare widget names as well, and build a array with the possible widget matches array
    // (which is used later if ID match fails)
    elseif($widget == $w['name']):
      $possible_matches[] = $w['id'];

    endif;

  // nothing found, assume it's the "Widget Name".
  if(!$callback):
    $valid_matches = array();
    foreach($sidebars_widgets[$sidebar] as $i => $w)
      foreach($possible_matches as $id) if($id == $w) $valid_matches[] = $w;

    if(!empty($valid_matches)) $widget = $number ? $valid_matches[$number-1] : $widget = $valid_matches[0];
    if($widget && isset($wp_registered_widgets[$widget]['callback'])) $callback = $wp_registered_widgets[$widget]['callback'];
  endif;

  // yey. we found it
  if($callback):
    ob_start();

    $params = array_merge(array(array_merge($wp_registered_sidebars[$sidebar], array('widget_id' => $widget, 'widget_name' => $wp_registered_widgets[$widget]['name']))), (array)$wp_registered_widgets[$widget]['params']);

    $classname_ = '';
    foreach ((array)$wp_registered_widgets[$widget]['classname'] as $cn)
      if (is_string($cn)) $classname_ .= '_'.$cn; elseif (is_object($cn)) $classname_ .= '_'.get_class($cn);
    $classname_ = ltrim($classname_, '_');
    $params[0]['before_widget'] = sprintf($params[0]['before_widget'], $widget, $classname_);
    $params = apply_filters('dynamic_sidebar_params', $params);

    if (is_callable($callback)) call_user_func_array($callback, $params);
    $output = ob_get_clean();

    // remove h3 if title = false
    if(!$title) $output = preg_replace('#<h3 class="title">(.*?)</h3>#', '', $output);
    return $output;
  else:
   return "widget instance not found: ".esc_attr($atts[0]);
  endif;
}

Usage:

Drop a widget in the "arbitrary widgets" sidebar, save it and you'll get the shortcodes :)


Get a custom field value through shortcodes

add_shortcode('field', 'shortcode_field');

function shortcode_field($atts){
  extract(shortcode_atts(array(
   'post_id' => NULL,
  ), $atts));

  if(!isset($atts[0])) return;
  $field = esc_attr($atts[0]);

  global $post;
  $post_id = (NULL === $post_id) ? $post->ID : $post_id;

  return get_post_meta($post_id, $field, true);
}

Usage:

  • [field "my_key"]
  • [field "my_key" post_id=1]

Get the TinyURL of a link through shortcodes

add_shortcode('tinyurl', 'shortcode_tinyurl'); 

function shortcode_tinyurl($atts){
  extract(shortcode_atts(array(
   'url' => get_permalink(),
   'title' => '',
   'rel' => 'nofollow'
  ), $atts));
  if(!$title) $title = $url;

  if (FALSE === ($cache = get_transient('tinyurl_'+md5($url)))):
    $cache = wp_remote_retrieve_body(wp_remote_get('http://tinyurl.com/api-create.php?url='.$url));

    set_transient('tinyurl_'+md5($url), $cache, 60*60*24); // 1 day cache, could be incresed
  endif;

  return '<a href="'.esc_url($cache).'" rel="'.esc_attr($rel).'">'.esc_attr($title).'</a>';
}

Usage:

  • [tinyurl]
  • [tinyurl url="http://google.com" title="google"]
share|improve this answer

Remove superfluous info and HTML within the <head> tag

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

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

Modify the Login Logo & Image URL Link

Tested on: WordPress 3.0.1

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

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

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

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

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

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

Include custom post types in "Right Now" admin dashboard

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

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

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

Include custom post types in the search results.

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

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

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

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

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

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

Pre-populating post types

Here is one for this collection.

////////////////////////////////////////////////////////////////////////////////////
// This auto populates post types and posts.
///////////////////////////////////////////////////////////////////////////////////

add_filter( 'default_content', 'my_editor_content' );

function my_editor_content( $content ) {

    global $post_type;

    switch( $post_type ) {
        case 'your_post_type_here': //auto populate
            $content = 'The content you want to pre-populate the post type with.';
break;
     }

    return $content;
}

This can come in handy for when you need to post the same info over and over again with slight differences.

share|improve this answer

Only show posts and media of the logged-in Author & fix the post/media counts on the filter bars.

Tested on: Wordpress 3.4.1

By default, WordPress allows Authors to see the titles of other users posts, unpublished drafts, and all media, even though they cannot be edited.

Use this code to only allow posts and media of the currently logged in Author to be displayed.

Unlike other solutions, this also fixes the post/media count on the filter bars (All|Published|Draft|Pending|Trash; All|Images|Videos|Unattached).

// Show only posts and media related to logged in author
add_action('pre_get_posts', 'query_set_only_author' );
function query_set_only_author( $wp_query ) {
    global $current_user;
    if( is_admin() && !current_user_can('edit_others_posts') ) {
        $wp_query->set( 'author', $current_user->ID );
        add_filter('views_edit-post', 'fix_post_counts');
        add_filter('views_upload', 'fix_media_counts');
    }
}

// Fix post counts
function fix_post_counts($views) {
    global $current_user, $wp_query;
    unset($views['mine']);
    $types = array(
        array( 'status' =>  NULL ),
        array( 'status' => 'publish' ),
        array( 'status' => 'draft' ),
        array( 'status' => 'pending' ),
        array( 'status' => 'trash' )
    );
    foreach( $types as $type ) {
        $query = array(
            'author'      => $current_user->ID,
            'post_type'   => 'post',
            'post_status' => $type['status']
        );
        $result = new WP_Query($query);
        if( $type['status'] == NULL ):
            $class = ($wp_query->query_vars['post_status'] == NULL) ? ' class="current"' : '';
            $views['all'] = sprintf(__('<a href="%s"'. $class .'>All <span class="count">(%d)</span></a>', 'all'),
                admin_url('edit.php?post_type=post'),
                $result->found_posts);
        elseif( $type['status'] == 'publish' ):
            $class = ($wp_query->query_vars['post_status'] == 'publish') ? ' class="current"' : '';
            $views['publish'] = sprintf(__('<a href="%s"'. $class .'>Published <span class="count">(%d)</span></a>', 'publish'),
                admin_url('edit.php?post_status=publish&post_type=post'),
                $result->found_posts);
        elseif( $type['status'] == 'draft' ):
            $class = ($wp_query->query_vars['post_status'] == 'draft') ? ' class="current"' : '';
            $views['draft'] = sprintf(__('<a href="%s"'. $class .'>Draft'. ((sizeof($result->posts) > 1) ? "s" : "") .' <span class="count">(%d)</span></a>', 'draft'),
                admin_url('edit.php?post_status=draft&post_type=post'),
                $result->found_posts);
        elseif( $type['status'] == 'pending' ):
            $class = ($wp_query->query_vars['post_status'] == 'pending') ? ' class="current"' : '';
            $views['pending'] = sprintf(__('<a href="%s"'. $class .'>Pending <span class="count">(%d)</span></a>', 'pending'),
                admin_url('edit.php?post_status=pending&post_type=post'),
                $result->found_posts);
        elseif( $type['status'] == 'trash' ):
            $class = ($wp_query->query_vars['post_status'] == 'trash') ? ' class="current"' : '';
            $views['trash'] = sprintf(__('<a href="%s"'. $class .'>Trash <span class="count">(%d)</span></a>', 'trash'),
                admin_url('edit.php?post_status=trash&post_type=post'),
                $result->found_posts);
        endif;
    }
    return $views;
}

// Fix media counts
function fix_media_counts($views) {
    global $wpdb, $current_user, $post_mime_types, $avail_post_mime_types;
    $views = array();
    $_num_posts = array();
    $count = $wpdb->get_results( "
        SELECT post_mime_type, COUNT( * ) AS num_posts 
        FROM $wpdb->posts 
        WHERE post_type = 'attachment' 
        AND post_author = $current_user->ID 
        AND post_status != 'trash' 
        GROUP BY post_mime_type
    ", ARRAY_A );
    foreach( $count as $row )
        $_num_posts[$row['post_mime_type']] = $row['num_posts'];
    $_total_posts = array_sum($_num_posts);
    $detached = isset( $_REQUEST['detached'] ) || isset( $_REQUEST['find_detached'] );
    if ( !isset( $total_orphans ) )
        $total_orphans = $wpdb->get_var("
            SELECT COUNT( * ) 
            FROM $wpdb->posts 
            WHERE post_type = 'attachment' 
            AND post_author = $current_user->ID 
            AND post_status != 'trash' 
            AND post_parent < 1
        ");
    $matches = wp_match_mime_types(array_keys($post_mime_types), array_keys($_num_posts));
    foreach ( $matches as $type => $reals )
        foreach ( $reals as $real )
            $num_posts[$type] = ( isset( $num_posts[$type] ) ) ? $num_posts[$type] + $_num_posts[$real] : $_num_posts[$real];
    $class = ( empty($_GET['post_mime_type']) && !$detached && !isset($_GET['status']) ) ? ' class="current"' : '';
    $views['all'] = "<a href='upload.php'$class>" . sprintf( __('All <span class="count">(%s)</span>', 'uploaded files' ), number_format_i18n( $_total_posts )) . '</a>';
    foreach ( $post_mime_types as $mime_type => $label ) {
        $class = '';
        if ( !wp_match_mime_types($mime_type, $avail_post_mime_types) )
            continue;
        if ( !empty($_GET['post_mime_type']) && wp_match_mime_types($mime_type, $_GET['post_mime_type']) )
            $class = ' class="current"';
        if ( !empty( $num_posts[$mime_type] ) )
            $views[$mime_type] = "<a href='upload.php?post_mime_type=$mime_type'$class>" . sprintf( translate_nooped_plural( $label[2], $num_posts[$mime_type] ), $num_posts[$mime_type] ) . '</a>';
    }
    $views['detached'] = '<a href="upload.php?detached=1"' . ( $detached ? ' class="current"' : '' ) . '>' . sprintf( __( 'Unattached <span class="count">(%s)</span>', 'detached files' ), $total_orphans ) . '</a>';
    return $views;
}
share|improve this answer

Here are some nice shortcodes for you to use:


1. Easy to add twitter & facebook share button Shortcode

function shreplz() {
   return '
    <div class="sharebox">
    <div class="twittme"><a href="https://twitter.com/share" class="twitter-share-button" data-count="horizontal">Tweet</a><script type="text/javascript" src="//platform.twitter.com/widgets.js"></script></div>
    <div class="shareface"><a name="fb_share"></a> <script src="http://static.ak.fbcdn.net/connect.php/js/FB.Share" type="text/javascript"></script></div>
    <br style="clear: left;" />
    </div>
   ';
}
add_shortcode('sharethis', 'shreplz');
// how to use: [sharethis]

2. Easy Remote site snapshot using Wordpress API shortcode

function wpr_snap($atts, $content = null) {
        extract(shortcode_atts(array(
            "snap" => 'http://s.wordpress.com/mshots/v1/',
            "url" => 'http://www.sagive.co.il',
            "alt" => 'My image',
            "w" => '400', // width
            "h" => '300' // height
        ), $atts));

    $img = '<img src="' . $snap . '' . urlencode($url) . '?w=' . $w . '&h=' . $h . '" alt="' . $alt . '"/>';
        return $img;
}

add_shortcode("snap", "wpr_snap");
//how to use: [snap url="http://www.example.com" alt="Cool Site!" w="300px" h="200px"]

3. Easy to use & embed iFrame Shortcode

function GenerateIframe( $atts ) {
    extract( shortcode_atts( array(
        'href' => 'http://the-url',
        'height' => '550px',
        'width' => '600px',     
    ), $atts ) );

    return '<iframe src="'.$href.'" width="'.$width.'" height="'.$height.'"> <p>Your Browser does not support Iframes.</p></iframe>';
}
add_shortcode('iframe', 'GenerateIframe');
// how to use: [iframe href="http://www.exmaple.com" height="480" width="640"]

4. Easy to include remote file / doc with Shortcode

function getfile_content( $atts ) {
  extract( shortcode_atts( array(
    'fileurl' => ''
  ), $atts ) );

  if ($fileurl!='')
    return @file_get_contents($fileurl);
}

add_shortcode( 'getfile', 'getfile_content' );
// how to use: [getfile fileurl="http://www.exmaple.com/somepage.html"]

.
Here are some Comments Related Snippets:

1. close the ability to comment globaly

function closeCommentsGlobaly($data) { return false; }
add_filter('comments_number', 'closeCommentsGlobaly');
add_filter('comments_open', 'closeCommentsGlobaly');

2. Give admin a different Css Class for he's comments

if (1 == $comment->user_id)
echo 'siteadmin'; // pick your class here

3. a really cool rich with data list of comments - gr8 for custom locked page

$comments = get_comments( array(
    'number'    => 10, // how many comments
    'status'    => 'approve' // type of comments
) );

foreach($comments as $eachComment){

// collect the data and assign it
$commentID = comment_ID;
$commentAuthorEmail = $eachComment->comment_author_email;
$commentPostId = $eachComment->comment_post_ID;
$commentPostTitle = get_the_title( $commentPostId );
$commentPostUrl = get_permalink( $commentPostId );
$comment_sidebarnumber = get_comments_number( $commentPostId );

global $wpdb;
$userCommentCount = $wpdb->get_var('SELECT COUNT('.$commentID.') FROM ' . $wpdb->comments. ' WHERE comment_author_email = "' . $commentAuthorEmail . '"');

    echo    '<div style="border: 1px solid #ccc; padding: 10px;">';
    echo    '<ul style="margin: 0px;">';
    echo    '<li>Name: '. $eachComment->comment_author .'</li>';
    echo    '<li>Commented about: <a href="'.$commentPostUrl.'">'. $commentPostTitle .'</a></li>';
    echo    '<li>Commented On: '. $eachComment->comment_date .'</li>';
    echo    '<li>Commneter Site: '. $eachComment->comment_author_email .'</</li>';
    echo    '<li>Commenter Email: '. $eachComment->comment_author_email .'</</li>';
    echo    '<li>This Commenter'. $eachComment->comment_author .' Commented '. $userCommentCount .' on your site</</li>';
    echo    '</ul>';
    echo    '<p style="padding: 10px;"><strong>'. $eachComment->comment_author .' wrote</strong>: '. $eachComment->comment_content .'</p>';
    echo    '</div>';

}
share|improve this answer

Remove Default Wordpress Meta Boxes

Tested on: Wordpress 3.0.1

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

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


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

Cross Taxonomy Tags Query

A cached query that outputs a get_tags() like HTML string of all tags for a given Taxonomy parameter defaulting to a Category. You can use $where_slug and $where_tax to get post tags filtered by any other taxonomy. SQL tested for WP 3.1 to WP 3.3.1.

function tags_by_other_taxonomy($where_slug,$where_tax = 'category',$bust_cache = false) {
    $cache_key = "{$where_slug}:{$where_tax}";
    $cache = get_transient('tags_by_other_taxonomy');
    $html = '';
    if( true !== $bust_cache and false !== $cache and isset($cache[$cache_key]) and !empty($cache[$cache_key]) ) {
            $html = $cache[$cache_key];
    } else {
        global $wpdb;
        $cat_id = $wpdb->get_var("SELECT tt.term_taxonomy_id FROM $wpdb->terms t INNER JOIN $wpdb->term_taxonomy tt ON t.term_id = tt.term_id WHERE t.slug = '{$where_slug}' AND tt.taxonomy = '{$where_tax}' LIMIT 1");
        if( !empty($cat_id) ) {
            $cat_posts = $wpdb->get_col("SELECT tr.object_id FROM $wpdb->term_relationships tr inner join $wpdb->posts p ON p.ID = tr.object_id WHERE term_taxonomy_id = {$cat_id} AND p.post_status = 'publish' AND p.post_type = 'post'");
            if( count($cat_posts) ) {
                $tags = $wpdb->get_results("SELECT DISTINCT t.name,t.slug FROM $wpdb->term_taxonomy tt
                                INNER JOIN $wpdb->term_relationships tr ON tt.term_taxonomy_id = tr.term_taxonomy_id
                                INNER JOIN $wpdb->terms t ON t.term_id = tt.term_id
                                WHERE tt.taxonomy = 'post_tag' and tr.object_id IN (".implode(',',$cat_posts) .')');
                $html = '<ul class="post-tags-'.$where_slug.'">';
                if( count($tags) ) {
                    foreach($tags as $tag)
                        $html .= '<li><a href="/tag/'.$tag->slug.'/" title="Posts tagged with '.$tag->name.'">'.$tag->name.'</a></li>';
                }
                $html .= '</ul>';
                if( !is_array($cache) )
                    $cache = array();
                $cache[$cache_key] = $html;
                set_transient('sc_cross_tax', $cache, 86400);
            }
        }
    }
    echo $html;
}

For example, get all tags for Published Posts in the news Category slug:

<?php echo tags_by_other_taxonomy('news'); ?>
share|improve this answer

Loading jQuery from the Google CDN

Tested on: Wordpress 3.0.1

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

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

if ( !is_admin() ) {

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

Remove the WordPress Version Info for Security

Tested on: Wordpress 3.0.1

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

Add Spam & Delete Links to Comments on Front End

Tested on: Wordpress 3.0.1

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

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

Delay the public posting to RSS Feed

Tested on: Wordpress 3.0.1

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

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

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

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

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

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

Add a custom class to the next and previous links

add_filter('next_posts_link_attributes', 'posts_link_attributes');
add_filter('previous_posts_link_attributes', 'posts_link_attributes');
function posts_link_attributes(){
    return 'class="styled-button"';
    }
share|improve this answer

List all constants for information and debugging

Tested on: Wordpress 3.0.1

Will only display the information if you are a logged in user

if ( is_user_logged_in() ) {
    print('<pre>');
    print_r( @get_defined_constants() );
    print('</pre>');
}

Here is version with optional filter that will partially match constant names and values:

function constants($filter = false) {

        $constants = get_defined_constants();

        if( $filter ) {

            $temp = array();

            foreach ( $constants as $key => $constant )
                if( false !== stripos( $key, $filter ) || false !== stripos( $constant, $filter ) )
                    $temp[$key] = $constant;

            $constants = $temp;
        }

        ksort( $constants );
        var_dump( $constants );
    }
share|improve this answer

Automatically create a new page upon activating a theme

if (isset($_GET['activated']) && is_admin()){
    $new_page_title = 'This is the page title';
    $new_page_content = 'This is the page content';
    $new_page_template = ''; //ex. template-custom.php. Leave blank if you don't want a custom page template.

//don't edit under this line
$page_check = get_page_by_title($new_page_title);
$new_page = array(
    'post_type' => 'page',
    'post_title' => $new_page_title,
    'post_content' => $new_page_content,
    'post_status' => 'publish',
    'post_author' => 1,
);
if(!isset($page_check->ID)){
    $new_page_id = wp_insert_post($new_page);
    if(!empty($new_page_template)){
        update_post_meta($new_page_id,'_wp_page_template', $new_page_template);
    }
}
share|improve this answer

Remove WordPress 3.3 Admin Bar Menu Items

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

Reference: http://pastebin.com/Wrk0JPxw

share|improve this answer

Add custom post types to archives page

function namespace_add_custom_types( $query ) {
if( is_category() || is_tag() && empty( $query->query_vars['suppress_filters'] ) ) {
$query->set( 'post_type', array(
 'post', 'your-custom-post-type-here'
            ));
      return $query;
    }
}
add_filter( 'pre_get_posts', 'namespace_add_custom_types' );
share|improve this answer

Sharpen Resized Images (only jpg)

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

function ajx_sharpen_resized_files( $resized_file ) {

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

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

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

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

    return $resized_file;
}   

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

Custom smilies (plugin)

/**
 * Smilies.
 */
function filter_smilies_src($img_src, $img, $siteurl) {
    return plugins_url('', __FILE__) . '/img/smilies/' . $img;
}
add_filter('smilies_src', 'filter_smilies_src', 1, 10);

Custom smilies (theme)

/**
 * Smilies.
 */
function filter_smilies_src($img_src, $img, $siteurl) {
    return get_bloginfo('stylesheet_directory') . '/images/smilies/' . $img;
}
add_filter('smilies_src', 'filter_smilies_src', 1, 10);
share|improve this answer

Automatically add a hidden custom field and associating value to a post when the post is published

add_action('publish_page', 'add_custom_field_automatically');
add_action('publish_post', 'add_custom_field_automatically');
function add_custom_field_automatically($post_ID) {
global $wpdb;
if(!wp_is_post_revision($post_ID)) {
    add_post_meta($post_ID, 'field-name', 'custom value', true);
}
}
share|improve this answer

Display the users that have submitted the most comments without a plugin

function top_comment_authors($amount = 5) {
global $wpdb;
$results = $wpdb->get_results('
    SELECT
    COUNT(comment_author_email) AS comments_count, comment_author_email, comment_author, comment_author_url
    FROM '.$wpdb->comments.'
    WHERE comment_author_email != "" AND comment_type = "" AND comment_approved = 1
    GROUP BY comment_author_email
    ORDER BY comments_count DESC, comment_author ASC
    LIMIT '.$amount
);
$output = "<ul>";
foreach($results as $result) {
    $output .= "<li>".$result->comment_author."</li>";
}
$output .= "</ul>";
echo $output;
}

Other options you can call: $result->comment_author_email $result->comments_count $result->comment_author_url

share|improve this answer

Adds a custom dropdown option to WP_NAV_MENUS where the user can select a predefined css class for each menu item

<?php function menu_item_class_select(){
    global $pagenow;
    if ($pagenow == "nav-menus.php"){
?>

<script>
jQuery(document).ready(function(){
    function create_dd(v){
        //create dropdown
        var dd = jQuery('<select class="my_class"></select>');
        //create dropdown options
        //array with the options you want
        var classes = ["","class1","class2","class3"];
        jQuery.each(classes, function(i,val) {
            if (v == val){
                dd.append('<option value="'+val+'" selected="selected">'+val+'</option>');
            }else{
                dd.append('<option value="'+val+'">'+val+'</option>');
            }
        });
        return dd;
    }
    jQuery(".edit-menu-item-classes").each(function() {
        //add dropdown
        var t = create_dd(jQuery(this).val());
        jQuery(this).before(t);
        //hide all inputs
        jQuery(this).css("display","none");
    });
    //update input on selection
    jQuery(".my_class").bind("change", function() {
        var v = jQuery(this).val();
        var inp = jQuery(this).next();
        inp.attr("value",v);
    });
});
</script>

<?php } }
add_action('admin_footer','menu_item_class_select');
?>

source: http://wordpress.stackexchange.com/a/33816/479

share|improve this answer

Output the contents of a widget outside the context of a sidebar using it's ID. The wrapping before/after HTML is not included. You need to know the specific ID of the widget you're angling for (ie 'text-5').

function widget_contents($id) {
    list($type,$number) = explode('-',$id);
    global $wp_registered_widgets;
    $wp_registered_widgets[$id]['callback'][0]->display_callback(array('widget_id'=>$id),$number);
}

You can peek at the output of wp_get_sidebars_widgets() if you aren't sure of the precise ID you need.

A more complete example lifted from /wp-includes/widgets.php under the dynamic_sidebar() function:

function render_widget($id) {
    global $wp_registered_widgets;
    $params = array_merge(
            array( array('widget_id' => $id, 'widget_name' => $wp_registered_widgets[$id]['name']) ),
            (array) $wp_registered_widgets[$id]['params']
    );
    $classname_ = '';
    foreach ( (array) $wp_registered_widgets[$id]['classname'] as $cn ) {
            if ( is_string($cn) )
                    $classname_ .= '_' . $cn;
            elseif ( is_object($cn) )
                    $classname_ .= '_' . get_class($cn);
    }
    $classname_ = ltrim($classname_, '_');
    $params[0]['before_widget'] = sprintf($params[0]['before_widget'], $id, $classname_);

    if ( is_callable($wp_registered_widgets[$id]['callback']) )
            call_user_func_array($wp_registered_widgets[$id]['callback'], $params);
}
share|improve this answer

is_tree() conditional Function

/* Adapted from csstricks with addition of
ancestors .... use = if(is_tree($id)) { // do stuff } ... Returns true if the
page is  = $id OR any of it's children OR descendants */

function is_tree($pid) {      // $pid = The ID of the page we're looking for pages underneath
  global $post;         // load details about this page
  $ancestors = get_post_ancestors($post);
  if(is_page()&&($post->post_parent==$pid||is_page($pid)||(in_array($pid,$ancestors))))
    return true;   // we're at the page or at a sub page
  else
    return false;  // we're elsewhere 
  };
share|improve this answer

Show template files being included

Display inline comment with Template File and get_template_part files being included when rendering pages. Handy for troubleshooting multipart templates.

add_action('all','template_snoop');
function template_snoop(){
    $args = func_get_args();
    if( !is_admin() and $args[0] ){
        if( $args[0] == 'template_include' ) {
            echo "<!-- Base Template: {$args[1]} -->\n";
        } elseif( strpos($args[0],'get_template_part_') === 0 ) {
            global $last_template_snoop;
            if( $last_template_snoop )
                echo "\n\n<!-- End Template Part: {$last_template_snoop} -->";
            $tpl = rtrim(join('-',  array_slice($args,1)),'-').'.php';
            echo "\n<!-- Template Part: {$tpl} -->\n\n";
            $last_template_snoop = $tpl;
        }
    }
}
share|improve this answer

Get Attributes of Given Thumbnail

Use this function with the loop to determine width, height and URL of a thumbnailed image. Very handy for assigning a thumbnailed image as a background element via inline CSS.

/**
* GET THUMBNAIL ATTRIBUTES
*
* Fetches width, heigth and URI of a thumbnail.
*
* @author Philip Downer <philip@manifestbozeman.com>
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* @version v1.0
*
* @param string $return Accepts 'path', 'width', or 'height'.
* @param string $size The thumbnail size corresponding to {@link add_image_size() WP core function}.
* @return mixed Returns the requested info, or if no 'Featured Image' assigned, returns 'false'.
*/
function get_thumb_attr($return,$size='thumbnail') {
    global $post;

    if (has_post_thumbnail($post->ID)) {
      $thumb = wp_get_attachment_image_src(get_post_thumbnail_id(), 'intro');
      if ( $return == 'path' ) { return $thumb[0]; }
      if ( $return == 'width' ) { return $thumb[1]; }
      if ( $return == 'height' ) { return $thumb[2]; }
    } else {
        return false;
    }
}//end function
share|improve this answer

Replace Default Gravatar with Custom Image

All you'll need to customize is the path to your default image.

function custom_gravatar($avatar_defaults) {
    $logo = get_bloginfo('template_directory') . '/images/icons/gravatar_logo.jpg'; //Change to whatever path you like.
    $avatar_defaults[$logo] = get_bloginfo('name');
    return $avatar_defaults;
}//END FUNCTION    
add_filter( 'avatar_defaults', 'custom_gravatar' );
share|improve this answer

Easy WordPress Security Fixes

Security through obscurity is the name of the game here. These functions do three different things.

  1. Remove the version string from the code. No point in telling folks what version we're running.
  2. Removes any error messages (Wrong Password, No Such User, etc.) from admin login screens
  3. When the admin posts a comment, a CSS class is added. This removes the admin name in comments.

    //REMOVE VERSION STRING FROM HEADER
    remove_action('wp_head', 'wp_generator');
    
    //HIDE LOGIN ERROR MESSAGES (Wrong Password, No Such User etc.)
    add_filter('login_errors',create_function('$a', "return null;"));
    
    // Remove admin name in comments class
    // Source: http://www.wprecipes.com/wordpress-hack-remove-admin-name-in-comments-class
    function remove_comment_author_class( $classes ) {
        foreach( $classes as $key => $class ) {
            if(strstr($class, "comment-author-")) {
                unset( $classes[$key] );
            }
        }
        return $classes;
    }
    add_filter( 'comment_class' , 'remove_comment_author_class' );
    
share|improve this answer

Disable Upgrade Now Message for Non-Administrators

I'm actually a big fan of NOT using this code. Instead, I prefer to allow customers to update their own WordPress installs. This helps keep the site up-to-date and forces me to write better code.

if ( !current_user_can( 'manage_options' ) ) {
  add_action( 'init', create_function( '$a', "remove_action( 'init', 'wp_version_check' );" ), 2 );
  add_filter( 'pre_option_update_core', create_function( '$a', "return null;" ) );
}
share|improve this answer

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