Andreas Hecht September 19th, 2017

The 26 Most Useful and Most Functional WordPress Snippets

WordPress becomes better with the plugins, as they allow you to fully customize your website to fulfill your needs. However, many functions can also be integrated without using a plugin. A simple snippet does the trick. Collecting all the required snippets can be pretty tedious, though. Thus, today, I’ll open my toolbox and list my favorite WordPress snippets for you.

Compatibility:

  • WordPress Version up from 4.6
  • PHP-Version 7.xx

Either copy the snippets into your active theme’s functions.php, or set up a page-specific custom plugin for this job.

Remember: Before you apply any changes to the functions.php, create a backup of the file. Don't alter the file using the WordPress editor. If something goes wrong, you won't have access to your website. Make your additions using an FTP access, directly on your web space.

The WordPress Tag Cloud is a popular tool for a blog’s sidebar. Your visitors can use it to easily find what they’re looking for. However, WordPress displays the tags in different sizes, which is not always a desired thing. Use this snippet to remove the inline styles.

<?php

/**
 * Remove style from Tag Clouds
 * @author Andreas Hecht
 */
function drweb_remove_tagcloud_inline_style($input){ 
    return preg_replace('/ style=("|\')(.*?)("|\')/','',$input); 
}
add_filter('wp_generate_tag_cloud', 'drweb_remove_tagcloud_inline_style',10,1); 

2 – Turn Off Your Self-referring Pingbacks

Pingbacks and trackbacks are not generally bad. They tell you if your articles were mentioned or linked on other websites. Sadly, WordPress has the bad habit of informing you about links of your articles on your own website. This snippet lets you turn off these annoying messages.

<?php

/**
 * Disable self pingbacks
 * 
 */
function evolution_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', 'evolution_no_self_ping' );

3 – Turn Off WordPress Emojis

Not everyone is a fan of the colorful emojis. If you don’t want to use emojis in your posts, you can deactivate this feature. Your blog’s performance will thank you.

<?php

/**
* Disable the emojis
*/
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;
}

4 – Turn Off the jQuery Migrate Script

jQuery Migrate is a script meant to create a downward compatibility of older jQuery applications. The “normal” and modern jQuery version does not support all old applications anymore. While this won’t affect more than 5% of all WordPress website, WordPress loads the pretty sizeable script by default. Here’s an easy way to turn it off:

<?php

/**
* Dequeue jQuery Migrate Script in WordPress.
*/
if ( ! function_exists( 'evolution_remove_jquery_migrate' ) ) :

function evolution_remove_jquery_migrate( &$scripts) {
    if(!is_admin()) {
        $scripts->remove( 'jquery');
        $scripts->add( 'jquery', false, array( 'jquery-core' ), '1.12.4' );
    }
}
add_filter( 'wp_default_scripts', 'evolution_remove_jquery_migrate' );
endif;

5 – Deactivate the WordPress oEmbed Function

The WordPress version 4.4 brought us the new function oEmbed, which is mainly meant to allow you to integrate foreign articles or pages into your posts with a simple link. If you don’t need this function, or you simply don’t want your articles to be able to be displayed in foreign posts at any time, just deactivate this function.

6 – Free the WordPress Header From Unnecessary Entries

WordPress loads a bunch of things via the wp_head() hook into the header of the WordPress themes. Some of them are very useful, some aren’t. Some just inflate the website unnecessarily. Here’s a small snippet to do some major cleaning up.

7 – Inject Post Images Into the RSS Feed

By default, WordPress doesn’t add post images to the RSS feed. This snippet changes that.

8 – Allow Additional File Formats For the Media Library

You want to upload special file formats to your WordPress media library, and you get an error message? Use this code, and your problem is solved. The code allows you to upload the file formats ZIPMOBIPDF, and EPUB. If you happen to need more formats, find the complete list of MIME types here.

9 – Freely Define the Length of the Excerpt

Sometimes, a very precise excerpt length is needed for a certain template. The following function lets you define this length freely. The good thing is that the excerpt length is not set globally, allowing each template to have its own length.

In the template, just exchange the tags and define the excerpt length:

10 – Responsive Videos – YouTube and Vimeo

If your theme doesn’t support responsive videos, setting up the support to do so can be done very quickly. A PHP function makes for an automatic embedding in a Div, while the CSS information makes sure there’s an optimal scaling at any resolution.

The necessary CSS:

11 – Setting Up WordPress Pagination Without a Plugin

Do you want to replace the “older posts | newer posts” with a cool list of numbers? No problem, as with WordPress version 4.1 you don’t need the popular plugin WP PageNavi anymore. Now, doing this is very easy to do using default means.

You can use this function directly within the index.php , and in the archive.php. However, creating a child theme to do so is advantageous.

To give the list a design, some CSS is needed. Here are the styles that I use every now and then. You need to adjust it to your blog colors:

12 – Custom Login Logo With a Custom Background Color

You are really proud of your WordPress website, and you put lots of effort into the design? Take it a step further, and adjust the logo on the login page. In combination with your own background color, this looks really nice.

13 – Change the Look of the First Paragraph

Your article will only look really cool when the first paragraph is designed in a different color and font. To do so, you don’t even need to switch into the text area of your editor, as WordPress itself can do that for you automatically. Two snippets do the trick:

The code above adds the class .opener to every article’s or page’s first paragraph. Now, a bit of CSS lets you control the paragraph’s formatting, as well as the “place” of action.

Or articles and pages display the first paragraph differently:

14 – User Signup With Email and Password Only

Since WordPress version 4.5, a user signup via email address and password is possible. In order to annoy hackers, and make WordPress a bit safer, you can sign up via email and password exclusively using this code.

15 – Prevent Users From Changing Their Passwords

The WordPress admin area is the heart and the lungs of your website. Make sure that the distributed passwords are very safe, giving attackers no chance. Users like to change the assigned passwords into very easy to remember, and very easy to hack versions, though. You can prevent that!

16 – Displaying Ads After the xx Paragraph

If you want to make money off your blog, you won’t get around using ads. You could use the popular Google Adsense, for example. This snippet displays your ads after a selected paragraph.

17 – Expanding Your User Profile With Further Social Media Accounts

The biographic information in your WordPress profile is pretty thin. You don’t have the option to link all of your social networks. With this code, you can add and display all of your social media accounts.

Use the following tag to display the new fields in the theme:

18 – Display a Category List With RSS Feeds

Sometimes, being able to display all categories with their respective RSS feed addresses can be handy. It gets even better when you are able to use a WordPress shortcode to display the list anywhere – even in the text widgets.

The Shortcode:

[categories-feed]

lets you display the list wherever you want to. It also works within widgets.

You can also use the shortcode in your theme:

19 – Display Related Posts Without a Plugin

The popular similar posts can easily be displayed without an inflated plugin with “many” functions. You need a PHP snippet, a child theme, and a bit of CSS.

After the code has been copied to the functions.php, a tag had to be added in the single.php, or the template that contains the loop of individual posts.

To make sure that the whole thing looks nice, some CSS is required:

20 – Creating a Sitemap.XML Without a Plugin

In combination with the Google Search Console (formerly Webmaster Tools), the sitemap.xml makes for a fast indexation of your website’s posts. Previously, you had to install a plugin in order to generate a sitemap.xml. With this code, you can forgo the plugin.

[blue-box text=”The sitemap is created for your posts, the pages, and the images in the media library.”]

21 – Make Post Images Mandatory

The following snippet could be very useful for blogs with multiple authors, as it makes post images required in order to be able to publish an article.

22 – Automatically Link Twitter Accounts

If you tend to link Twitter accounts in your posts, you’ll love this snippet. When entering @account, it will automatically link the according Twitter account.

23 – Prevent Automatic Linking in User Comments

Every URL entered in the comments is automatically turned into a link by WordPress. This can become a problem, as not all of those links are worth being linked on your blog. The following snippet turns the URLs into pure text.

24 – Load the Entire JavaScript in the Footer

WordPress normally loads the JavaScript into the header of your website. This slows down the page buildup by a lot. With this code, the entire JavaScript is loaded in the footer, allowing the site to build up faster.

25 – Create a Breadcrumb Navigation Without a Plugin

You don’t need an overloaded plugin for a breadcrumb navigation. A few lines of code are all it takes.

The Tag For the Invocation in the Theme

In the theme, the navigation can be integrated using a simple function invocation. The right files to do that would be the header.php, the index.php, or the single.php, depending on the theme.

26 – Display Custom Post Types in the Categories and Tags

Custom Post Types are an extremely useful tool for the design of an extensive website with many functions. However, they are not automatically included in the categories and tags. If you start a search, this will always leave you with an error. These two snippets integrate your custom post types into the WordPress search function.

The Snippet for the Categories:

The Snippet for the Tags:

Conclusion

I hope you discovered some useful snippets for you and your WordPress. If this article ends up being successful, I might follow up with an article on the most useful WooCommerce snippets. Let me know whether that interests you.

Andreas Hecht

Andreas Hecht is a journalist and specialist for WordPress and WordPress Security. He roams the web since its inception. He has published an ebook on WordPress Security, which you might want to take a look at.

One comment

  1. In snippet 3 – Turn Off WordPress Emojis – the 3rd function to remove DNS prefetch did not work for me, but this did:
    add_filter( ’emoji_svg_url’, ‘__return_false’ );

Sorry, Comments are closed...