BLOG

Super Useful Code Snippets for WordPress

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

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;
}
}
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;
}
}
remove_filter('comment_text', 'make_clickable', 9);
function SearchFilter($query) {
if ($query->is_search) {
$query->set('post_type', 'post');
}
return $query;
}

add_filter('pre_get_posts','SearchFilter');
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;" ) );
function wps_registration_redirect(){
return home_url( '/finished/' );
}
add_filter( 'registration_redirect', 'wps_registration_redirect' );
function my_wc_redirect( $redirect, $user ) {
    // $user_id = $user->ID;
    // if(user_can( $user,  )) { // With the user object you can access their saved carts etc. too.
    // $redirect = get_permalink();
    // }
    // OR without depending on the user
    // $redirect = 'https://www.example.com/';
    return $redirect;
}
add_filter( 'woocommerce_login_redirect', 'my_wc_redirect', 10, 2 );
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');
add_filter( 'show_admin_bar', '__return_false' );
function my_custom_login_logo() { 
echo 'url';
 }
 add_action('login_head', 'my_custom_login_logo');
function custom_admin_logo() { 
echo 'url';
 }
 add_action('admin_head', 'custom_admin_logo');
function remove_footer_admin () { 
echo 'Some cool text or link'; } 
add_filter('admin_footer_text', 'remove_footer_admin');
add_filter( 'avatar_defaults', 'newgravatar' ); 
function newgravatar ($avatar_defaults) { 
$myavatar = get_bloginfo('template_directory') . '/images/gravatar.gif'; 
$avatar_defaults[$myavatar] = "WPBeginner"; 

return $avatar_defaults;
function my_excerpt_length($length) 
{
return 65; 
}
add_filter('excerpt_length', 'my_excerpt_length');
function new_excerpt_more($text) 
{  
return ' [...]'; 
}
add_filter('excerpt_more', 'new_excerpt_more');
// 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');
function remove_comment_fields($fields) {
    unset($fields['url']);
    return $fields;
}
add_filter('comment_form_default_fields','remove_comment_fields');
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;
}
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);
add_filter( 'author_link', 'my_author_link' );

function my_author_link() {
	return home_url( 'page-name-here' );
}
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 );
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;
        }
    }
}
function itsme_disable_feed() {
wp_die( __( ‘No feed available, please visit the homepage!' ) );
}

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);
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');
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');
add_action( 'wp_footer', 'awts_openlinks_innnewtab' ); // Write our JS below here
function awts_openlinks_innnewtab() { ?>
$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?";
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' );
function excludePages( $query ) {
if ( $query->is_search ) {
	$query->set( 'post_type', 'post' );
}
	return $query;
}
add_filter( 'pre_get_posts','excludePages' );
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');
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');
// 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' );
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);
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' );
function wpc_auto_redirect_after_logout(){  
  wp_redirect( home_url() );  
  exit();  
}  
add_action('wp_logout','wpc_auto_redirect_after_logout');
function wpc_redirect_after_comment(){  
      wp_redirect('/thank-you/');  
      exit();  
}  
add_filter('comment_post_redirect', 'wpc_redirect_after_comment');
add_action('wp_footer', 'external_link_tab');
function external_link_tab(){
?>
 8, 'largest' => 22, 'unit' => 'pt', 'number' => 999,
        'format' => 'array', 'orderby' => 'name', 'order' => 'ASC',
        'exclude' => '', 'include' => '');
$tags = get_tags($args);
?>

Security

function wpb_remove_version() {
return '';
}
add_filter('the_generator', 'wpb_remove_version');
function disable_wordpress_loginerrors(){
  return 'Oops Login Error !';
}
add_filter( 'login_errors', 'disable_wordpress_loginerrors' );
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);
add_filter('json_enabled', '__return_false');
add_filter('json_jsonp_enabled', '__return_false');
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

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;
}
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 );
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');
    }
}
if(!defined('WP_POST_REVISIONS')) define('WP_POST_REVISIONS',10);
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 );
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);
Share on facebook
Facebook
Share on twitter
Twitter
Share on linkedin
LinkedIn
Share on email
Email
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 thoughts on “Super Useful Code Snippets for WordPress”

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

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

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

Leave a Comment

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