Super Useful Code Snippets for WordPress

BLOG
Super Useful Code Snippets for WordPress

Image Credit: @clemhirdt

Wordpress offers it’s users a ton of built-in functionality. There are thousands of free and premium plugins that can expand on the framework to include more robust features. In addition to all of this awesomeness there are handy dandy code snippets that can be used to to achieve even more customization options. I. Love. Code. Snippets.

Code snippets are like teeny tiny plugins that allow you to further manipulate settings or other elements allowing you to enhance performance, security and design.

I’ve compiled a list of some snippets below that you may find useful and I will continue to update this post every now and again. If you have any suggest, please feel free to contact me or post a comment below.

Please note: Use at your own risk. If anything goes wonky simply remove the code snippet.

General

Block Dashboard Except for Admin Users

add_action( ‘init’, ‘blockusers_init’ );
function blockusers_init() {
if ( is_admin() && ! current_user_can( ‘administrator’ ) &&
! ( defined( ‘DOING_AJAX’ ) && DOING_AJAX ) ) {
wp_redirect( home_url() );
exit;
}
}

Allow Login with Username or Email

function login_with_email_address($username) {
$user = get_user_by('email',$username);
if(!empty($user->user_login))
$username = $user->user_login;
return $username;
}
add_action('wp_authenticate','login_with_email_address');

function change_username_wps_text($text){
if(in_array($GLOBALS[‘pagenow’], array(‘wp-login.php’))){
if ($text == ‘Username’){$text = ‘Username / Email’;}
}
return $text;
}
add_filter( ‘gettext’, ‘change_username_wps_text’ );

Disable Active Links from Comments

remove_filter('comment_text', 'make_clickable', 9);

Exclude Pages from Search

function SearchFilter($query) {
if ($query->is_search) {
$query->set('post_type', 'post');
}
return $query;
}

add_filter('pre_get_posts','SearchFilter');

Disable WP Search Function

function fb_filter_query( $query, $error = true ) {

if ( is_search() ) {
$query->is_search = false;
$query->query_vars[s] = false;
$query->query[s] = false;

// to error
if ( $error == true )
$query->is_404 = true;
}
}

add_action( 'parse_query', 'fb_filter_query' );
add_filter( 'get_search_form', create_function( '$a', "return null;" ) );

Redirect New Registered Users to a Specific Page

function wps_registration_redirect(){
return home_url( '/finished/' );
}
add_filter( 'registration_redirect', 'wps_registration_redirect' );


		

Change Number of Search Results Shown

function limit_posts_per_search_page() {
	if ( is_search() )
		set_query_var('posts_per_archive_page', 20); 
}

add_filter('pre_get_posts', 'limit_posts_per_search_page');

Remove Admin Bar from Front End

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

Customize WP Login Logo

function my_custom_login_logo() { 
echo 'url';
 }
 add_action('login_head', 'my_custom_login_logo');

Customize WP Dashboard Logo

function custom_admin_logo() { 
echo 'url';
 }
 add_action('admin_head', 'custom_admin_logo');

Change WP Dashboad Footer Text

function remove_footer_admin () { 
echo 'Some cool text or link

WordPress

'; 
} 
add_filter('admin_footer_text', 'remove_footer_admin');

Change Default Gravatar

add_filter( 'avatar_defaults', 'newgravatar' ); 
function newgravatar ($avatar_defaults) { 
$myavatar = get_bloginfo('template_directory') . '/images/gravatar.gif'; 
$avatar_defaults[$myavatar] = "WPBeginner"; 

return $avatar_defaults;

Change Excerpt Link

function my_excerpt_length($length) 
{
	return 65; 
}
add_filter('excerpt_length', 'my_excerpt_length');

Change ‘Read More’ Post Text

function new_excerpt_more($text) 
{  
	return ' [...]'; 

}
add_filter('excerpt_more', 'new_excerpt_more');

Enable Maintenance Mode

// This will only block users who are NOT an administrator from viewing the website.

function wp_maintenance_mode(){

if(!current_user_can('edit_themes') || !is_user_logged_in()){

wp_die('Maintenance, please come back soon.', 'Maintenance – please come back soon.', array('response' => '503'));

}

}

add_action('get_header', 'wp_maintenance_mode');

Remove URL Field from Comment Form

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

Set Minimum Characters for Comments

add_filter( 'preprocess_comment', 'minimal_comment_length' );
function minimal_comment_length( $commentdata ) {
	$minimalCommentLength = 20;
	if ( strlen( trim( $commentdata['comment_content'] ) ) < $minimalCommentLength )
        {
		wp_die( 'All comments must be at least ' . $minimalCommentLength . ' characters long.' );
        }
	return $commentdata;
}

Allow PHP in Text Widget

function php_text($text) {
 if (strpos($text, '<' . '?') !== false) { ob_start(); eval('?' . '>' . $text);
 $text = ob_get_contents();
 ob_end_clean();
 }
 return $text;
}
add_filter('widget_text', 'php_text', 99);

Redirect Author Archive to Specific Page

add_filter( 'author_link', 'my_author_link' );

function my_author_link() {
	return home_url( 'page-name-here' );
}

Mark Comments with Long URLs as Spam

function rkv_url_spamcheck( $approved , $commentdata ) {
    return ( strlen( $commentdata['comment_author_url'] ) > 50 ) ? 'spam' : $approved;
  }

  add_filter( 'pre_comment_approved', 'rkv_url_spamcheck', 99, 2 );

Redirect to Post if Search Results Returns One Result

add_action('template_redirect', 'redirect_single_post');
function redirect_single_post() {
    if (is_search()) {
        global $wp_query;
        if ($wp_query->post_count == 1 && $wp_query->max_num_pages == 1) {
            wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );
            exit;
        }
    }
}

Disable RSS Feed

function itsme_disable_feed() {
wp_die( __( ‘No feed available, please visit the <a href=”‘. esc_url( home_url( ‘/’ ) ) .'”>homepage</a>!’ ) );
}

add_action(‘do_feed’, ‘itsme_disable_feed’, 1);
add_action(‘do_feed_rdf’, ‘itsme_disable_feed’, 1);
add_action(‘do_feed_rss’, ‘itsme_disable_feed’, 1);
add_action(‘do_feed_rss2’, ‘itsme_disable_feed’, 1);
add_action(‘do_feed_atom’, ‘itsme_disable_feed’, 1);
add_action(‘do_feed_rss2_comments’, ‘itsme_disable_feed’, 1);
add_action(‘do_feed_atom_comments’, ‘itsme_disable_feed’, 1);

Create Dashboard Widget

function custom_dashboard_widgets() {
global $wp_meta_boxes;
wp_add_dashboard_widget('custom_help_widget', 'Dashboard Widget', 'custom_dashboard_help');
}
function custom_dashboard_help() {
echo '
Hello! I am a dashboard widget.
';
}
add_action('wp_dashboard_setup', 'custom_dashboard_widgets');

Create Custom Post Type

function create_custom_post() {
	register_post_type( 'custom-post', // slug for custom post type
		array(
		'labels' => array(
			'name' => __( 'Custom Post' ),
		),
		'public' => true,
		'hierarchical' => true, 
		'has_archive' => true,
		'supports' => array(
			'title',
			'editor',
			'excerpt',
			'thumbnail'
		), 
		'can_export' => true,
		'taxonomies' => array(
				'post_tag',
				'category'
		)
	));
}
add_action('init', 'create_custom_post');

Open All Links in a New Window

add_action( 'wp_footer', 'awts_openlinks_innnewtab' ); // Write our JS below here
function awts_openlinks_innnewtab() { ?>

Display Number of Comments

$commcount = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->comments WHERE comment_approved = '1'"); 

if (0 < $commcount) $commcount = number_format($commcount); 
echo "Our users have made ".$commcount." comments, care to join in?";

Change Reply Text for Comments

function bs_modified_comment_reply_text( $link ) {
 $link = str_replace( 'Reply', 'Respond', $link );
 return $link;
 }
add_filter( 'comment_reply_link', 'bs_modified_comment_reply_text' );

Exclude Custom Post Type from Search

function excludePages( $query ) {
if ( $query->is_search ) {
	$query->set( 'post_type', 'post' );
}
	return $query;
}
add_filter( 'pre_get_posts','excludePages' );

Insert Content After Post

function add_post_content($content) {
	if(!is_feed() && !is_home()) {
		$content .= '
This article is copyright © '.date('Y').' '.bloginfo('name').'
';
	}
	return $content;
}
add_filter('the_content', 'add_post_content');

Rename 'Post' to 'Article'

function wpc_change_post_to_article( $translated ) {  
$translated = str_ireplace('Post','Article',$translated );// ireplace is PHP5 only  
return $translated;  
}  
// hook the translation filters  
add_filter('gettext','wpc_change_post_to_article');  
add_filter('ngettext','wpc_change_post_to_article');

Restrict Content on Your Site to Members

// usage: [member] only logged in users can see this text[/member]  
    function wpc_restrict_content( $atts, $content = null ) {  
        if ( is_user_logged_in() &&   
            !is_null($content) &&   
            !is_feed()   
             ) {  

            return $content;  
        } else {  

            return __( 'Sorry, this content is only available for logged users.', 'yourtheme' );  
        }  
    }  
    add_shortcode( 'member', 'wpc_restrict_content' );

Sharpen Resized JPGS

// usage: [member] only logged in users can see this text[/member]  
    function wpc_restrict_content( $atts, $content = null ) {  
        if ( is_user_logged_in() &&   
            !is_null($content) &&   
            !is_feed()   
             ) {  

            return $content;  
        } else {  

            return __( 'Sorry, this content is only available for logged users.', 'yourtheme' );  
        }  
    }  
    add_shortcode( 'member', 'wpc_restrict_content' );

Create Admin Dropdown Menu

function wpc_add_toolbar_menu($admin_bar){  
    $admin_bar->add_menu( array(  
        'id'    => 'my-link',  
        'title' => 'My link',  
        'href'  => '#',  
        'meta'  => array(  
            'title' => __('My Link'),  
        ),  
    ));  
    $admin_bar->add_menu( array(  
        'id'    => 'my-sub-link',  
        'parent' => 'my-link',  
        'title' => 'My Sub Menu Link',  
        'href'  => '#',  
        'meta'  => array(  
            'title' => __('My Sub Menu Link'),  
            'target' => '_blank',  
            'class' => 'my_menu_item_class'  
        ),  
    ));  
    $admin_bar->add_menu( array(  
        'id'    => 'my-second-sub-link',  
        'parent' => 'my-link',  
        'title' => 'My Second Sub Menu Link',  
        'href'  => '#',  
        'meta'  => array(  
            'title' => __('My Second Sub Menu Link'),  
            'target' => '_blank',  
            'class' => 'my_menu_item_class'  
        ),  
    ));  
}  
add_action('admin_bar_menu', 'wpc_add_toolbar_menu', 100);

Create Link in Admin Bar

function wpc_adminbar_custom_links() {  
    global $wp_admin_bar;  
    $wp_admin_bar->add_menu( array(  
        'parent' => false, // use 'false' for a root menu, or pass the ID of the parent menu  
        'id' => 'settings_general', // link ID, defaults to a sanitized title value  
        'title' => __('General Options'), // link title  
        'href' => admin_url( 'options-general.php'), // name of file  
        'meta' => array( 'html' => '', 'class' => '', 'onclick' => '', 'target' => '', 'title' => '' )  
    ));  
}  
add_action( 'wp_before_admin_bar_render', 'wpc_adminbar_custom_links' );

Redirect to Home After Logout

function wpc_auto_redirect_after_logout(){  
  wp_redirect( home_url() );  
  exit();  
}  
add_action('wp_logout','wpc_auto_redirect_after_logout');

Redirect Comment Author After Posting Comment

function wpc_redirect_after_comment(){  
      wp_redirect('/thank-you/');  
      exit();  
}  
add_filter('comment_post_redirect', 'wpc_redirect_after_comment');

Open External Links in New Tab

add_action('wp_footer', 'external_link_tab');
function external_link_tab(){
?>
<script type="text/javascript">
//<![CDATA[
jQuery(document).ready(function($) {
$('a').each(function() {
var a = new RegExp('/' + window.location.host + '/');
if(!a.test(this.href)) {
$(this).click(function(event) {
event.preventDefault();
event.stopPropagation();
window.open(this.href, '_blank');
});
}
});
});
//]]>
</script><?php
};

Security

Remove WP Version Info

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

Remove Login Error Messages

function disable_wordpress_loginerrors(){
  return 'Oops Login Error !';
}
add_filter( 'login_errors', 'disable_wordpress_loginerrors' );

Remove Unnecessary Elements from Head

remove_action('wp_head', 'wlwmanifest_link');
remove_action('wp_head', 'rsd_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', 'feed_links_extra', 3 );
remove_action('wp_head', 'feed_links', 2 );
remove_action('wp_head', 'parent_post_rel_link', 10, 0 );
remove_action('wp_head', 'start_post_rel_link', 10, 0 );
remove_action('wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);

Disable JSON Rest API

add_filter('json_enabled', '__return_false');
add_filter('json_jsonp_enabled', '__return_false');

Block Dashboard Except for Admin Users

add_action( ‘init’, ‘blockusers_init’ );
function blockusers_init() {
if ( is_admin() && ! current_user_can( ‘administrator’ ) &&
! ( defined( ‘DOING_AJAX’ ) && DOING_AJAX ) ) {
wp_redirect( home_url() );
exit;
}
}

Optimization

Remove Emoji Script

function disable_emojis() {
remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );
remove_action( 'wp_print_styles', 'print_emoji_styles' );
remove_action( 'admin_print_styles', 'print_emoji_styles' ); 
remove_filter( 'the_content_feed', 'wp_staticize_emoji' );
remove_filter( 'comment_text_rss', 'wp_staticize_emoji' ); 
remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' );
add_filter( 'tiny_mce_plugins', 'disable_emojis_tinymce' );
add_filter( 'wp_resource_hints', 'disable_emojis_remove_dns_prefetch', 10, 2 );
}
add_action( 'init', 'disable_emojis' );

/**
* Filter function used to remove the tinymce emoji plugin.
* 
* @param array $plugins 
* @return array Difference betwen the two arrays
*/
function disable_emojis_tinymce( $plugins ) {
if ( is_array( $plugins ) ) {
return array_diff( $plugins, array( 'wpemoji' ) );
} else {
return array();
}
}

/**
* Remove emoji CDN hostname from DNS prefetching hints.
*
* @param array $urls URLs to print for resource hints.
* @param string $relation_type The relation type the URLs are printed for.
* @return array Difference betwen the two arrays.
*/
function disable_emojis_remove_dns_prefetch( $urls, $relation_type ) {
if ( 'dns-prefetch' == $relation_type ) {
/** This filter is documented in wp-includes/formatting.php */
$emoji_svg_url = apply_filters( 'emoji_svg_url', 'https://s.w.org/images/core/emoji/2/svg/' );

$urls = array_diff( $urls, array( $emoji_svg_url ) );
}

return $urls;
}

Remove Query String from Static Resources

function _remove_script_version( $src ){ 
$parts = explode( '?', $src ); 
return $parts[0]; 
} 
add_filter( 'script_loader_src', '_remove_script_version', 15, 1 ); 
add_filter( 'style_loader_src', '_remove_script_version', 15, 1 );

Replace WP jquery with Google CDN

add_action('init','jquery_register');

function jquery_register() {
    if(!is_admin()) {
    wp_deregister_script('jquery');
    wp_register_script('jquery',('https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js'),false,null,true);
    wp_enqueue_script('jquery');
    }
}

Limit Post Revisions in Database

if(!defined('WP_POST_REVISIONS')) define('WP_POST_REVISIONS',10);

Defer Javascript

function js_async_attr($tag){

# Do not add defer or async attribute to these scripts
$scripts_to_exclude = array('script1.js', 'script2.js', 'script3.js');

foreach($scripts_to_exclude as $exclude_script){
 if(true == strpos($tag, $exclude_script ) )
 return $tag; 
}

# Defer or async all remaining scripts not excluded above
return str_replace( ' src', ' defer="defer" src', $tag );
}
add_filter( 'script_loader_tag', 'js_async_attr', 10 );

Remove Obsolete Bloat from Database

function remove_default_userfields( $contactmethods ) {
unset($contactmethods['aim']);
unset($contactmethods['jabber']);
unset($contactmethods['yim']);
return $contactmethods;
}
add_filter('user_contactmethods','remove_default_userfields',10,1);

Aloha, I am a Hawaii based freelance web designer and developer located on the beautiful island of Maui. Where the skies are blue, the palm trees sway and spam is a pretty big deal.

My articles are geared towards site design and development, nifty wordpress tips and gadgets and other ramblings of webthings amusement.

3 Comments
  • Captain Krik
    Posted at 02:55h, 16 July Reply

    Hi, I noticed that with the latest version of php the code below is deprecated
    add_filter(‘login_errors’,create_function(‘$a’, “return null;”));
    or better, is the “create function” deprecated. There is any way to fix it? I’m not able to find any solution for this specific snippet.
    Thanks in advance
    Krik

    • Joy
      Posted at 10:21h, 16 July Reply

      Hi! Thanks for your feedback. You can use this snippet instead:

      function disable_wordpress_loginerrors(){
      return 'Oops Login Error !';
      }
      add_filter( 'login_errors', 'disable_wordpress_loginerrors' );

      • Captain Krik
        Posted at 21:52h, 16 July Reply

        What can I say Joy? Finally it works perfectly!
        In the web there is no solutions like this.
        Thank you so much. YaaG (You are a Genius)
        Krik

Post A Comment