29 Code Snippets for WordPress Users

Tired of installing tons of WordPress plugins for small features? You can use code snippets to do certain things without a dedicated plugin. Generally the functions.php file is the place to add code snippes.

If you don’t want to edit PHP file and want to gain more fine control over code snippets? You should try out Code Snippets plugin. With Code Snippets, you can easily add PHP code snippets to your WordPress site without custom snippets in theme’s functions.php file. Search Code Snippets in WordPress’s Add Plugins page and install it. You can start adding code snippet just like how you write post.

We collected some very useful code snippets for WordPress. All can be used with Code Snippets plugin or added it directly to PHP file.

  1. Auto update plug and theme

1
2
add_filter( 'auto_update_plugin', '__return_true' );
add_filter( 'auto_update_theme', '__return_true' );
  1. Remove all HTML Comments and space

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
function callback($buffer) {
$search = array(
'/\n/',
'/\>[^\S ]+/s', // strip whitespaces after tags, except space
'/[^\S ]+\</s', // strip whitespaces before tags, except space
'/(\s)+/s', // shorten multiple whitespace sequences
'/<!--(.|s)*?-->/'
);

$replace = array(
'',
'>',
'<',
'\\1',
''
);

#$buffer = preg_replace('/<!--(.|s)*?-->/', '', $buffer);
$buffer = preg_replace($search, $replace, $buffer);
return $buffer;
}
function buffer_start() {
ob_start("callback");
}
function buffer_end() {
ob_end_flush();
}
add_action('get_header', 'buffer_start');
add_action('wp_footer', 'buffer_end', 9999);
  1. Add DNS Prefetching

1
2
3
4
5
6
7
8
9
//* Adding DNS Prefetching
function stb_dns_prefetch() {
echo '<meta http-equiv="x-dns-prefetch-control" content="on">
<link rel="dns-prefetch" href="//pagead2.googlesyndication.com" />
<link rel="dns-prefetch" href="//googleads.g.doubleclick.net" />
<link rel="dns-prefetch" href="//www.google-analytics.com" />
<link rel="dns-prefetch" href="//s.gravatar.com/" />';
}
add_action('wp_head', 'stb_dns_prefetch', 1);
  1. Stop loading wp-emoji-release.min.js

1
2
remove_action('wp_head', 'print_emoji_detection_script', 7);
remove_action('wp_print_styles', 'print_emoji_styles');
  1. Prefer loading jquery JavaScript with async and defer tag

1
2
3
4
5
6
7
8
if (!is_admin()) {
add_filter( 'script_loader_tag', function ( $tag, $handle ) {
if ( strpos( $tag, "jquery.min.js" ) || strpos( $tag, "jquery.js") ) {
return $tag;
}
return str_replace( ' src', ' async src', $tag );
}, 10, 2 );
}
  1. Load CDN jQuery from Google

1
2
3
4
5
6
7
8
9
10
11
// Load CDN jQuery 
add_action( 'wp_enqueue_scripts', 'register_jquery' );
function register_jquery() {
if (!is_admin() && $GLOBALS['pagenow'] != 'wp-login.php') {
// comment out the next two lines to load the local copy of jQuery
wp_deregister_script('jquery');
wp_register_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js', false, '3.2.1');
wp_enqueue_script('jquery');
}
}
// end
  1. Remove jQuery-Migrate script from header (New plugin will not have incompatibility issue)

Remove migrate script
1
2
3
4
5
6
7
8
add_filter( 'wp_default_scripts', 'remove_jquery_migrate' );
function remove_jquery_migrate( &$scripts)
{
if(!is_admin()) {
$scripts->remove( 'jquery');
$scripts->add( 'jquery', false, array( 'jquery-core' ), '1.10.2' );
}
}
  1. No self pings

1
2
3
4
5
6
7
8
// No Self Pings
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' );
  1. Add p tag to <!--more-->

tag detection
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function has_more()
{
global $post;
if ( empty( $post ) ) return;

if ($pos=strpos($post->post_content, '<!--more-->')) {
return true;
} else {
return false;
}
}

//add p tag to more tag
function add_p_tag($link){
return "<p>$link</p>";
}
add_filter('the_content_more_link', 'add_p_tag');
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function inject_ad_text_after_n_chars($content) {
// insert after the first </a> after x characters
$after_character = 1;
if (is_single()) {
$before_content = substr($content, 0, $after_character);
$after_content = substr($content, $after_character);
$after_content = explode('</p>', $after_content);
$text = '<ins class="adsbygoogle"
style="display:block"
data-ad-client="your id"
data-ad-slot="your ad slot"
data-ad-format="auto"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script></p>';
array_splice($after_content, 1, 0, $text);
$after_content = implode('', $after_content);
return $before_content . $after_content;
}
else {
return $content;
}
}
add_filter('the_content', 'inject_ad_text_after_n_chars', 13);
  1. Delay auto closing p tag to fix some problems.

auto closing p tag to fix some problems.
1
2
remove_filter( 'the_content', 'wpautop' );
add_filter( 'the_content', 'wpautop' , 12);
  1. Show Media upload path

Media upload
1
2
3
if(get_option('upload_path')=='wp-content/uploads' || get_option('upload_path')==null) {
update_option('upload_path',WP_CONTENT_DIR.'uploads');
}
  1. Image SEO, with size and height info

get_post_image ($post_id
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// select the post content from the db
$image_id = get_post_thumbnail_id();
$image_url = wp_get_attachment_image_src($image_id,'large');
$the_image_src = $image_url[0];

// if src found, then create a new img tag

if(strlen($the_image_src)) {
if(strlen($img_script)) {

// if the src starts with http/https, then strip out server name


if(preg_match("/^(http(|s):\/\/)/", $the_image_src)) {
$the_image_src = preg_replace("/^(http(|s):\/\/)/", '', $the_image_src);
$frags = split("\/", $the_image_src);
array_shift($frags);
$the_image_src = '/' . join("/", $frags);
}
$the_image = '<img class="' . $class . '" alt="' . $alt . '" src="' . $img_script . $the_image_src . '" width="' . $width . '" height="' . $height . '"/>';
}
else {
$the_image = '<img class="' . $class . '" alt="' . $alt . '" src="' . $the_image_src . '" width="' . $width . '" height="' . $height . '" width="' . $width . '" height="' . $height . '"/>';
}
}

// if there's no image
else
return false;

return $the_image;
}
Nofollow comments line
1
2
3
4
5
6
7
8
#function add_nofollow_to_comments_popup_link(){
# return ' rel="nofollow" ';}
#add_filter( 'comments_popup_link_attributes', 'add_nofollow_to_comments_popup_link' );

add_filter( 'get_comment_author_link', 'rv_remove_comment_author_link', 10, 3 );
function rv_remove_comment_author_link( $return, $author, $comment_ID ) {
return $author;
}
  1. Remove junk header

Remove junk
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#remove_action('wp_head', 'wp_enqueue_scripts', 1);
#add_action('wp_footer', 'wp_enqueue_scripts', 5);
function ft_rtt_remove_title_attribute( $output ){
$output = preg_replace('/title=\"(.*?)\"/','',$output);
return $output;
}
add_filter('wp_list_categories','ft_rtt_remove_title_attribute');
add_filter('wp_list_pages','ft_rtt_remove_title_attribute');
add_filter('the_category', 'ft_rtt_remove_title_attribute' );
add_filter('comment_ID', 'ft_rtt_remove_title_attribute' );

function wpbeginner_remove_version() {
return '';
}
add_filter('the_generator', 'wpbeginner_remove_version');
add_filter('show_admin_bar', '__return_false');
remove_action('wp_head','rsd_link');
remove_action('wp_head','wlwmanifest_link');
remove_action( 'wp_head', 'index_rel_link' );
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 );
remove_action( 'wp_head', 'rel_canonical' );
remove_action( 'wp_head', 'wp_shortlink_wp_head', 10, 0 );
remove_action( 'wp_head', 'noindex', 1 );
remove_filter('comment_text', 'make_clickable', 9);
#Remove Wordpress Comment Feed Link from header
#Display the links to the extra feeds such as category feeds
remove_action('wp_head', 'feed_links_extra', 3);
#Display the links to the general feeds: Post and Comment Feed
remove_action('wp_head', 'feed_links', 2);

$qmr_work_tags = array(
'the_title',
'the_content',
'the_excerpt',
'comment_text',
'list_cats',
'single_post_title',
'comment_author',
'term_name',
'link_name',
'link_description',
'link_notes',
'bloginfo',
'wp_title',
'widget_title',
'term_description',
'category_description',
'widget_text'
);

foreach ( $qmr_work_tags as $qmr_work_tag ) {
remove_filter ($qmr_work_tag, 'wptexturize');
}
  1. Remove category in url

Remove category, together with plugin
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function fix_slash( $string, $type )
{
global $wp_rewrite;
if ( $wp_rewrite->use_trailing_slashes == false )
{
if ( $type != 'single' && $type != 'category' )
return trailingslashit( $string );

if ( $type == 'single' && ( strpos( $string, '.html/' ) !== false ) )
return trailingslashit( $string );

if ( $type == 'category' && ( strpos( $string, 'category' ) !== false ) )
{
$aa_g = str_replace( "/category/", "/", $string );
return trailingslashit( $aa_g );
}
if ( $type == 'category' )
return trailingslashit( $string );
}
return $string;
}

add_filter( 'user_trailingslashit', 'fix_slash', 55, 2 );
  1. Add SEO title attributes next post link, previous post link

Title attributes to next and previous post link functions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
add_filter('next_post_link','add_title_to_next_post_link');
function add_title_to_next_post_link($link) {
global $post;
$post = get_post($post_id);
$next_post = get_next_post();
$title = $next_post->post_title;
$link = str_replace("rel=", " title='".$title."' rel=", $link);
return $link;
}

add_filter('previous_post_link','add_title_to_previous_post_link');
function add_title_to_previous_post_link($link) {
global $post;
$post = get_post($post_id);
$previous_post = get_previous_post();
$title = $previous_post->post_title;
$link = str_replace("rel=", " title='".$title."' rel=", $link);
return $link;
}
  1. Remove rel from category tag

Remove rel
1
2
3
4
5
6
function remove_rel($result) {
$result = str_replace(' rel="category tag"', 'rel="tag"', $result);
return $result;
}
add_filter('wp_list_categories', 'remove_rel');
add_filter('the_category', 'remove_rel');
  1. Remove query strings from static resources

query strings from static resources
1
2
3
4
5
6
7
8
9
10
11
12
function ewp_remove_script_version( $src ){
return remove_query_arg( 'ver', $src );
}
add_filter( 'script_loader_src', 'ewp_remove_script_version', 15, 1 );
add_filter( 'style_loader_src', 'ewp_remove_script_version', 15, 1 );

#remove header recent comment style
add_action('widgets_init', 'my_remove_recent_comments_style');
function my_remove_recent_comments_style() {
global $wp_widget_factory;
remove_action('wp_head', array($wp_widget_factory->widgets['WP_Widget_Recent_Comments'], 'recent_comments_style'));
}
  1. Add alt tags to thumbnail

'add_attachment', 'my_set_image_meta_upon_image_upload' );
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
function my_set_image_meta_upon_image_upload( $post_ID ) {

// Check if uploaded file is an image, else do nothing

if ( wp_attachment_is_image( $post_ID ) ) {

$my_image_title = get_post( $post_ID )->post_title;

// Sanitize the title: remove hyphens, underscores & extra spaces:
$my_image_title = preg_replace( '%\s*[-_\s]+\s*%', ' ', $my_image_title );

// Sanitize the title: capitalize first letter of every word (other letters lower case):
$my_image_title = ucwords( strtolower( $my_image_title ) );

// Create an array with the image meta (Title, Caption, Description) to be updated
// Note: comment out the Excerpt/Caption or Content/Description lines if not needed
$my_image_meta = array(
'ID' => $post_ID, // Specify the image (ID) to be updated
'post_title' => $my_image_title, // Set image Title to sanitized title
//'post_excerpt' => $my_image_title, // Set image Caption (Excerpt) to sanitized title
'post_content' => $my_image_title, // Set image Description (Content) to sanitized title
);

// Set the image Alt-Text
update_post_meta( $post_ID, '_wp_attachment_image_alt', $my_image_title );

// Set the image meta (e.g. Title, Excerpt, Content)
wp_update_post( $my_image_meta );

}
}
  1. Add pre tag wrapper to code tag, and editor button

pre tag
1
2
3
4
5
6
7
8
add_action('admin_print_footer_scripts','eg_quicktags');
function eg_quicktags() {
?>
<script type="text/javascript" charset="utf-8">
QTags.addButton( 'eg_pre', 'Code with Pre','<pre><code>', '</code></pre>', 'q' );
</script>
<?php
}
  1. Login page tweak

no_wordpress_errors(){
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
add_filter( 'login_errors', 'no_wordpress_errors');

function my_login_logo_one() {
?>
<style type="text/css">
body.login div#login h1 a {display: none; !important;}
</style>
<?php
}
add_action( 'login_enqueue_scripts', 'my_login_logo_one' );

// changing the logo link from wordpress.org to your site
function mb_login_url() { return home_url(); }
add_filter( 'login_headerurl', 'mb_login_url' );

// changing the alt text on the logo to show your site name
function mb_login_title() { return get_option( 'blogname' ); }
add_filter( 'login_headertitle', 'mb_login_title' );
  1. Remove wp version param from any enqueued scripts

remove wp version param from any enqueued scripts
1
2
3
4
5
function remove_wp_ver_css_js( $src ) {
if ( strpos( $src, 'ver=' . get_bloginfo( 'version' ) ) )
$src = remove_query_arg( 'ver', $src );
return $src;
}
  1. Add X-UA-Compatible header

1
2
3
4
5
6
function add_http_header($headers) {
$headers['X-UA-Compatible'] = 'IE=edge,chrome=1';
return $headers;
}

add_filter('wp_headers', 'add_http_header');
  1. Prevent WordPress from participating in Pingback Denial of Service Attacks

Disable xmlrcp/pingback
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
add_filter( 'xmlrpc_enabled', '__return_false' );
add_filter( 'pre_update_option_enable_xmlrpc', '__return_false' );
add_filter( 'pre_option_enable_xmlrpc', '__return_zero' );

// Disable trackbacks
add_filter( 'rewrite_rules_array', function( $rules ) {
foreach( $rules as $rule => $rewrite ) {
if( preg_match( '/trackback\/\?\$$/i', $rule ) ) {
unset( $rules[$rule] );
}
}
return $rules;
});


// Disable X-Pingback HTTP Header.
add_filter('wp_headers', function($headers, $wp_query){
if(isset($headers['X-Pingback'])){
unset($headers['X-Pingback']);
}
return $headers;
}, 11, 2);


add_filter( 'xmlrpc_methods', function($methods){
unset( $methods['pingback.ping'] );
unset( $methods['pingback.extensions.getPingbacks'] );
unset( $methods['wp.getUsersBlogs'] ); // Block brute force discovery of existing users
unset( $methods['system.multicall'] );
unset( $methods['system.listMethods'] );
unset( $methods['system.getCapabilities'] );
return $methods;
});
  1. Include thumbnail (post-thumb) in RSS feed

INCLUDES THE THUMBNAIL IN OUR RSS FEED
1
2
3
4
5
6
7
8
9
function insertThumbnailRSS($content) {
global $post;
if ( has_post_thumbnail( $post->ID ) ){
$content = '<p>' . get_the_post_thumbnail( $post->ID, 'post-thumb', array( 'alt' => get_the_title(), 'title' => get_the_title()) ) . '</p>' . $content;
}
return $content;
}
add_filter('the_excerpt_rss', 'insertThumbnailRSS');
add_filter('the_content_feed', 'insertThumbnailRSS');
Page Scroll When Clicking the More Link
1
2
3
4
5
function remove_more_link_scroll( $link ) {
$link = preg_replace( '|#more-[0-9]+|', '', $link );
return $link;
}
add_filter( 'the_content_more_link', 'remove_more_link_scroll' );
Image URLs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
add_filter('image_send_to_editor','image_to_relative',5,8);

function image_to_relative($html, $id, $caption, $title, $align, $url, $size, $alt)
{
$sp = strpos($html,"src=") + 5;
$ep = strpos($html,"\"",$sp);

$imageurl = substr($html,$sp,$ep-$sp);

$relativeurl = str_replace(["http://", "https://"],"",$imageurl);
$sp = strpos($relativeurl,"/");
$relativeurl = substr($relativeurl,$sp);

$html = str_replace($imageurl,$relativeurl,$html);

return $html;
}

If you have server control, you can use this to stop spam.
Stop Automated Comment Spam with Nginx

Automated Comment Spam with Nginx
1
2
3
4
function set_post_cookie() {
echo '<script>document.cookie = "_pass=1; max-age=1800; path=/; secure";</script>' . "";
}
add_action( 'comment_form', 'set_post_cookie', 100 );
Connect to existing AWS AppSync API from a React Application Easy Dual WAN Load Balancing with MikroTik RouterOS PCC

Comments