24 Awesome WordPress Code Snippets

Posted OnFeb 21, 2014     CategoryDevelopment     CommentsNo comment

Here we have 24 awesome code snippets to help speed up your WordPress Theme development. Unless otherwise noted, you can just put these straight into functions.php

Remove the URL field from the WordPress Comment Form

function wpkb_remove_comment_fields($fields) {
    unset($fields['url']);
    return $fields;
}
add_filter('comment_form_default_fields','remove_comment_fields');

Add Featured Images to WordPress Feeds

function wpkb_rss_post_thumbnail($content) {
	global $post;
	if(has_post_thumbnail($post->ID)) {
		$content = get_the_post_thumbnail($post->ID) . $content;
	}
	return $content;
}
add_filter('the_excerpt_rss', 'rss_post_thumbnail');
add_filter('the_content_feed', 'rss_post_thumbnail');

Add Titles to previous_post_link & next_post_link

Make your modifications in single.php, preferably in a child theme.

 
	$p = get_adjacent_post(false, '', true);
	if(!empty($p)) echo '<div class="prev"><a href="' . get_permalink($p->ID) . '" title="' . $p->post_title . '">' . $p->post_title . '</a></div>';
 
	$n = get_adjacent_post(false, '', false);
	if(!empty($n)) echo '<div class="next"><a href="' . get_permalink($n->ID) . '" title="' . $n->post_title . '">' . $n->post_title . '</a></div>'; 

Add a Class to the Last Post in a WordPress Loop

// Add a class to the last post in a loop
function wpkb_last_post_class($classes){
	global $wp_query;
	if(($wp_query->current_post+1) == $wp_query->post_count) $classes[] = 'last';
	return $classes;
}
add_filter('post_class', 'wpkb_last_post_class');

Move the Admin Bar to the bottom

function wpkb_move_admin_bar() {
    echo '
    <style type="text/css">
    body { 
    margin-top: -28px;
    padding-bottom: 28px;
    }
    body.admin-bar #wphead {
       padding-top: 0;
    }
    body.admin-bar #footer {
       padding-bottom: 28px;
    }
    #wpadminbar {
        top: auto !important;
        bottom: 0;
    }
    #wpadminbar .quicklinks .menupop ul {
        bottom: 28px;
    }
    </style>';
}
// on backend area
add_action( 'admin_head', 'wpkb_move_admin_bar' );
// on frontend area
add_action( 'wp_head', 'wpkb_move_admin_bar' );

Create a Shortcode

function my_shortcode_function(){
echo '<p>My Shortcode is Alive!</p>';
}// end my_shortcode_function
add_shortcode('my_shortcode', 'my_shortcode_function');

Enable Shortcodes in Widgets

add_filter('widget_text', 'do_shortcode');

Remove Default WordPress Metaboxes for Posts

// REMOVE META BOXES 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 the Default WordPress Meta Boxes for Pages

// REMOVE META BOXES PAGES
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');

Change the Excerpt Length

function new_excerpt_length($length) { 
    return 100;
}

add_filter('excerpt_length', 'new_excerpt_length');

Queries, Time and Memory for Optimization

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} -->" ;
}
add_action( 'wp_footer', 'performance', 20 );<br/>

Mod the Login Logo and Image URL HREF

// change the login link
add_filter( 'login_headerurl', 'login_header_url' );
function login_header_url( $url ) {
    $url = home_url( '/' );//make this whatever you want
    return $url;
}
 
// change the title
add_filter( 'login_headertitle', 'login_header_title' );
function login_header_title( $title ) {
  $title = get_bloginfo( 'name' );
  return $title;
}
  
// change the login image
add_action( 'login_head', 'namespace_login_style' );
function login_style() {
  echo '<style>.login h1 a { 
  background-image: url( ' . get_template_directory_uri() .  
  '/images/logo.png ) !important; }</style>'; 
} 

Include Custom Post Types in Search Results

function search_it_all( $query ) { 
 if ( $query->is_search ) {  
 $query->set( 'post_type', array( 'site', 'plugin', 'theme', 'person' )); }  
 return $query; 
} 
add_filter( 'the_search_query', 'search_it_all' ); 

Remove the WordPress Version Info

function version_removal() { 
    return ''; 
} 
add_filter('the_generator', 'version_removal');

Add Custom User Profile Fields

function custom_profile_fields( $contactmethods ) {

  $contactmethods['contact_phone_office']     = 'Office Phone';
  $contactmethods['contact_phone_mobile']     = 'Mobile Phone';
  $contactmethods['contact_office_fax']       = 'Office Fax'; 
  $contactmethods['address_line_1']       = 'Address Line 1';
  $contactmethods['address_line_2']       = 'Address Line 2 (optional)';
  $contactmethods['address_city']         = 'City';
  $contactmethods['address_state']        = 'State';
  $contactmethods['address_zipcode']      = 'Zipcode';
  return $contactmethods;
}
add_filter('user_contactmethods','custom_profile_fields',10,1);

Enable Thumbnails in Your Theme

// Enable thumbnails
add_theme_support( 'post-thumbnails' );
set_post_thumbnail_size(200, 200, true); // Normal post thumbnails

Enable a Widgetized Sidebar

// Enable widgetized sidebar

if ( function_exists('register_sidebar') )
	register_sidebar(array(
	'before_widget' => '<aside>',
	'after_widget' => '</aside>',
	'before_title' => '<h1>',
	'after_title' => '</h1>',
));

Remove the Admin Bar from the Front End

// Remove the admin bar from the front end
add_filter( 'show_admin_bar', '__return_false' );

Add Custom Menus to WordPress

// Add custom menus
register_nav_menus( array(
  'primary' => __( 'Primary Navigation', 'wpfme' ),
  //'example' => __( 'Example Navigation', 'wpfme' ),
) );

Change the Number of Search Results

//change amount of posts on the search page - set here to 100
function wpkb_search_results_perpage( $query ) {
	global $wp_the_query;
	if ( ( ! is_admin() ) && ( $query === $wp_the_query ) && ( $query->is_search() ) ) {
	$query->set( 'wpkb_search_results_per_page', 100 );
	}
	return $query;
}
add_action( 'pre_get_posts',  'wpkb_search_results_per_page'  );

Create a Permalinks after the Excerpt

//create a permalink after the excerpt
function wpkb_replace_excerpt($content) {
  return str_replace('[...]',
  '<a class="readmore" href="'. get_permalink() .'">Continue Reading</a>',
  $content);
}
add_filter('the_excerpt', 'wpfme_replace_excerpt');

Obscure Login Messages

// Obscure login screen error messages
function wpkb_error_obscure(){ return '<strong>Sorry</strong>: Think you have gone wrong somwhere!';}
add_filter( 'login_errors', 'wpkb_error_obscure' );

Disable the Theme and Plugin Editor in the Dashboard

// Disable the theme / plugin text editor in Admin
define('DISALLOW_FILE_EDIT', true);

Leave a Reply

Your email address will not be published. Required fields are marked *

Send this to friend