Enhance Any Website: Best Code Snippets for WordPress

Enhance Any Website_ Best Code Snippets for WordPress

What You'll Learn

Key Highlights

  • Discover how simple code snippets can supercharge your WordPress site.
  • Learn to customize your site easily without relying on tons of plugins.
  • Find snippets for SEO, speed optimization, security, and more!
  • We’ll guide you on how to safely add these snippets to your site.
  • Level up your WordPress game – no coding expertise needed.

If you want to improve your WordPress site beyond the basic setup without using tons of plugins, this is for you! You don’t need to be a coding expert to make great changes! With some easy code snippets, you can add cool features, increase your site’s speed, and strengthen security.

This blog will look at some useful code snippets that will help your WordPress site reach the next level. And the best part? You can add most of these without using a code snippets plugin—just some simple PHP! However, the easiest way to add these snippets is by using a lightweight plugin called Code Snippets.

Top Essential Code Snippets for WordPress

Let’s start with some important code snippets that can quickly enhance your WordPress site. These snippets are great for beginners. They are easy to understand and solve common needs for WordPress customization.

Don’t worry if you are not a coding expert, all you have to do is copy and paste…

Remove Google Fonts

Google Fonts can make your site’s text look nice, but they can also slow it down. If you want to speed things up, think about removing Google Fonts and using system fonts instead.

You can do this by adding this simple code snippet using the Code Snippets plugin. This snippet will remove the Google Fonts stylesheets. By doing this, your site will not load those extra fonts, which can help your page load faster.

add_filter( 'elementor/frontend/print_google_fonts', '__return_false' );

Disable Gutenberg Editor (use Classic Editor)

To turn off the Gutenberg editor and go back to the classic editor in WordPress, just follow a simple process. First, install the Classic Editor plugin. This will let you easily switch back to the interface you know well. Using this plugin helps you keep your preferred way of working. You won’t have to deal with any confusing changes. This keeps your user experience nice and smooth.

add_filter('gutenberg_can_edit_post', '__return_false', 5);
add_filter('use_block_editor_for_post', '__return_false', 5);

Ensures Custom Font Loads

This one is strictly for Elementor Pro. Sometimes, to make sure your custom fonts load properly in Elementor Pro, you need a little help. A code snippet can help by adding your custom font file and including it in your WordPress theme.

This ensures the font loads correctly and consistently on your site, which boosts the user experience. A small change like this can greatly improve how your brand looks.

add_filter( 'elementor_pro/custom_fonts/font_display', function( $current_value, $font_family, $data ) {
    return 'swap';
}, 10, 3 );

Remove Unused Java Sript

Over time, your WordPress site can gather unnecessary JavaScript files from themes and plugins. These extra files can clutter your code and make your pages slower.

A code snippet can help you find and remove these files. This will make your site faster and more streamlined. It’s smart to do regular code revisions like this to keep your site performing well.

/**
* We will Dequeue the jQuery UI script as example.
*
* Hooked to the wp_print_scripts action, with a late priority (99),
* so that it is after the script was enqueued.
*/
function wp_remove_scripts() {
    // check if user is admin
    if (current_user_can( 'update_core' )) {
        return;
    } else {
        // Check for the page you want to target
        if ( is_page( 'homepage' ) ) {
            // Remove Scripts
            wp_dequeue_style( 'jquery-ui-core' );
        }
    }
}
add_action( 'wp_enqueue_scripts', 'wp_remove_scripts', 99 );

Remove Unused CSS

Just like JavaScript, extra unused CSS can make your site’s code heavy. This usually occurs from themes or plugins that add many styles you may not use.

You can add a snippet to your header or footer. An even better option is to put it in your child theme’s stylesheet. This will help you find and remove unused CSS styles. It makes your site’s code cleaner and could speed up loading times.

function exclude_specific_css_files($src, $handle) {
    // List of CSS file URLs to exclude from minification
    $excluded_css_files = array(
        '/wp-content/plugins/elementor/assets/css/frontend-lite.min.css',
        '/wp-content/plugins/elementor-pro/assets/css/frontend-lite.min.css',
    );

    // Check if the current CSS file URL matches any of the excluded URLs
    foreach ($excluded_css_files as $excluded_css_file) {
        if (strpos($src, $excluded_css_file) !== false) {
            return $src; // Return the original unminified CSS file
        }
    }

    // If the CSS file is not in the excluded list, proceed with minification
    return minify_css_content($src);
}

function minify_css_content($content) {
    $content = preg_replace('/\s+/', ' ', $content); // Remove extra whitespaces
    $content = str_replace(array("\r\n", "\r", "\n", "\t"), '', $content); // Remove newlines and tabs

    return $content;
}

add_filter('style_loader_src', 'exclude_specific_css_files', 10, 2);

Add a Purge Cache Button

Clearing your site’s cache can often feel like a hassle. Luckily, with a simple code snippet, you can make it easier. This code lets you add a “Purge Cache” button right in your WordPress admin bar.

Now, you can quickly clear your cache whenever you change something on your site. Use a code snippet plugin, like Code Snippets, to make this even simpler.

/*
Plugin Name: Purge Cache
Description: Adds a button to the WordPress dashboard to clear the object cache
*/

add_action( 'admin_bar_menu', 'add_purge_cache_button', 999 );

function add_purge_cache_button( $wp_admin_bar ) {
    if ( ! current_user_can( 'manage_options' ) ) {
        return;
    }

    $args = array(
        'id'    => 'purge-cache',
        'title' => 'Purge Cache',
        'href'  => '#',
        'meta'  => array( 'class' => 'purge-cache' )
    );
    $wp_admin_bar->add_node( $args );
}

add_action( 'admin_footer', 'add_purge_cache_script' );

function add_purge_cache_script() {
    if ( ! current_user_can( 'manage_options' ) ) {
        return;
    }
    ?>
    
    <?php
}

add_action( 'wp_ajax_purge_cache', 'purge_cache_callback' );

function purge_cache_callback() {
    global $wp_object_cache;
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_die();
    }

    wp_cache_flush();

    wp_die();
}

Allow SVG Files Upload

SVG files are great for website images because they can be scaled up or down without losing quality. However, WordPress does not let you upload SVG files by default because of security issues. But, you can safely enable this feature by using a code snippet.

By adding a few simple lines of code, you can allow SVG uploads in your WordPress media library. Just like adding a “Purge Cache” button to your admin bar, you can use a code snippets plugin to manage this easily.

/**
 * Allow SVG uploads for administrator users.
 *
 * @param array $upload_mimes Allowed mime types.
 *
 * @return mixed
 */
add_filter(
    'upload_mimes',
    function ( $upload_mimes ) {
        // By default, only administrator users are allowed to add SVGs.
        // To enable more user types edit or comment the lines below but beware of
        // the security risks if you allow any user to upload SVG files.
        if ( ! current_user_can( 'administrator' ) ) {
            return $upload_mimes;
        }

        $upload_mimes['svg']  = 'image/svg+xml';
        $upload_mimes['svgz'] = 'image/svg+xml';

        return $upload_mimes;
    }
);

/**
 * Add SVG files mime check.
 *
 * @param array        $wp_check_filetype_and_ext Values for the extension, mime type, and corrected filename.
 * @param string       $file Full path to the file.
 * @param string       $filename The name of the file (may differ from $file due to $file being in a tmp directory).
 * @param string[]     $mimes Array of mime types keyed by their file extension regex.
 * @param string|false $real_mime The actual mime type or false if the type cannot be determined.
 */
add_filter(
    'wp_check_filetype_and_ext',
    function ( $wp_check_filetype_and_ext, $file, $filename, $mimes, $real_mime ) {

        if ( ! $wp_check_filetype_and_ext['type'] ) {

            $check_filetype  = wp_check_filetype( $filename, $mimes );
            $ext             = $check_filetype['ext'];
            $type            = $check_filetype['type'];
            $proper_filename = $filename;

            if ( $type && 0 === strpos( $type, 'image/' ) && 'svg' !== $ext ) {
                $ext  = false;
                $type = false;
            }

            $wp_check_filetype_and_ext = compact( 'ext', 'type', 'proper_filename' );
        }

        return $wp_check_filetype_and_ext;

    },
    10,
    5
);

Top Advanced Code Snippets to Elevate Your WordPress Website

Ready to improve your WordPress site? These advanced snippets help you have more control over how your site works, its SEO, and how users feel while visiting.

Though these snippets may seem a little tricky, they give you strong ways to perfectly adjust your WordPress site. Remember to take your time, back up your files, and feel free to try new things!

1. Customizing the Login Page for Enhanced Branding

Your WordPress login page is important, even if it’s often ignored. It is a great chance to show off your brand. Instead of the standard WordPress logo, you can use custom code. This will let you add your logo, brand colors, and a unique background image to your login screen.

Making this small change can greatly improve how professional your site looks. You can also use CSS to give style to the login form and button.

Keep in mind that even small branding details can help create a strong and professional online presence.

/**
 * Customizes the WordPress login page for enhanced branding.
 */

// Change the login logo URL to your site's homepage
add_filter( 'login_headerurl', function() {
    return home_url();
});

// Change the login logo title to your site's name
add_filter( 'login_headertext', function() {
    return get_bloginfo('name');
});

// Add custom styling to the login page
add_action( 'login_enqueue_scripts', function() {
    ?>
    <style type="text/css">
        /* Change the background color of the login page */
        body.login {
            background-color: #f0f4f8; /* Replace with your brand color */
        }

        /* Change the login logo */
        .login h1 a {
            background-image: url('<?php echo get_stylesheet_directory_uri(); ?>/images/custom-logo.png');
            background-size: contain;
            width: 100%;
            height: 100px;
        }

        /* Style the login form */
        .login form {
            background-color: #ffffff;
            border: 1px solid #d1d8e0;
            padding: 20px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            border-radius: 8px;
        }

        /* Customize the login button */
        .login .button-primary {
            background-color: #0073e6;
            border-color: #0073e6;
            box-shadow: none;
            text-shadow: none;
        }
        .login .button-primary:hover {
            background-color: #005bb5;
            border-color: #005bb5;
        }

        /* Customize links on the login page */
        .login #nav a, .login #backtoblog a {
            color: #0073e6;
        }
        .login #nav a:hover, .login #backtoblog a:hover {
            color: #005bb5;
        }
    </style>
    <?php
});
        

2. Optimizing Website Speed with Lazy Load Images

Images can slow down how fast a page loads. Lazy loading is a method that makes images load later. They will only appear when the user scrolls down to see them on the page.

You can use a simple code snippet to add lazy loading to your WordPress website. This change can make your page load much faster, especially if your site has many images. By loading images only when they are in view, you can speed up the initial load time. This leads to a better experience for your visitors.

// Add lazy loading to all images
function add_lazy_loading_to_images($content) {
    // Add loading="lazy" to each image in the content
    $content = preg_replace('/<img(?![^>]+loading=["\'](?:lazy|eager)["\'])/', '

3. Securing Your Site with a Simple Security Headers Snippet

Security should always be a priority. You can improve your WordPress site’s safety with a simple code snippet. This snippet adds important security headers.

These headers help by telling browsers how to manage your site’s content. They can also prevent common attacks, such as cross-site scripting (XSS). While one solution can’t fully secure your site, adding these security headers is a quick and effective way to make your online presence safer.

This small change can significantly protect your site and your visitors.

// Add security headers to improve site security
function add_security_headers() {
    header('X-Content-Type-Options: nosniff'); // Prevent MIME-type sniffing
    header('X-Frame-Options: SAMEORIGIN'); // Protect against clickjacking
    header('X-XSS-Protection: 1; mode=block'); // Enable XSS protection in older browsers
    header('Strict-Transport-Security: max-age=31536000; includeSubDomains'); // Force HTTPS
    header('Referrer-Policy: no-referrer-when-downgrade'); // Control referrer information
    header('Permissions-Policy: camera=(), microphone=(), geolocation=()'); // Restrict certain features
}
add_action('send_headers', 'add_security_headers');

Explanation of Each Header

  1. X-Content-Type-Options: Prevents MIME-type sniffing, which can help avoid certain types of attacks.
  2. X-Frame-Options: Protects against clickjacking by only allowing the site to be framed by the same origin.
  3. X-XSS-Protection: Enables cross-site scripting (XSS) protection in older browsers.
  4. Strict-Transport-Security: Forces HTTPS on the site, ensuring secure connections.
  5. Referrer-Policy: Controls referrer information sent with requests, adding privacy.
  6. Permissions-Policy: Restricts browser features like the camera, microphone, and geolocation.

4. Require a Featured Image for Posts

This code ensures that posts cannot be published unless a featured image is set. If a user tries to publish a post without a featured image, the post status is automatically changed to draft and a persistent error message is displayed on the admin dashboard. The message includes an “X” button that allows users to dismiss it, providing a clear indication of the requirement.

When editing a post that lacks a featured image, a warning message appears at the top of the editor, reminding the user to add an image.

Add this to your functions.php folder.


// Require Featured Image for Posts Only
function require_featured_image_for_posts($post_id) {
    // Skip autosaves and revisions
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if (wp_is_post_revision($post_id)) return;

    // Only require featured image for posts with publish status
    if (get_post_type($post_id) == 'post' && get_post_status($post_id) == 'publish') {
        if (!has_post_thumbnail($post_id)) {
            // Unset the publish status and set to draft
            remove_action('save_post', 'require_featured_image_for_posts'); // Avoid infinite loop
            wp_update_post(array('ID' => $post_id, 'post_status' => 'draft'));
            add_action('admin_notices', function() {
                echo '

Error: Please set a featured image before publishing.

‘; }); } } } add_action(‘save_post’, ‘require_featured_image_for_posts’); // Display error message on the editor screen if no featured image is set function featured_image_warning_for_posts() { global $post; if (get_post_type($post) == ‘post’) { if (!has_post_thumbnail($post->ID)) { echo ‘

Reminder: Please add a featured image to publish this post.

‘; } } } add_action(‘edit_form_after_title’, ‘featured_image_warning_for_posts’); 

Essential Tips for Safely Adding Code Snippets to WordPress

Before we get into the complicated code, let’s chat about safety! Customizing a WordPress site with code is fun, but you need to be careful.

It’s kind of like fixing up your home. You might be able to paint a wall by yourself, but you’d get a pro for the electrical work, wouldn’t you? Here are some tips to help you add code snippets safely to your WordPress site.

Just Use a Plugin

Adding you code snippets using a plugin

While adding these code snippets manually might be the better option, if you are a noobie or WordPress beginner, you might just want to simply use a WordPress plugin like Code Snippets.

Go to the WordPress directory and install the Code Snippets plugin. Add a new snippet for each of these and that’s it. Just make sure you are adding them in the correct folder (Functions.php)

Understanding the Functions.php File and Its Importance

The functions.php file is the control center for your WordPress theme. It holds the code that adds features and functions to your site. If you want to add code snippets, this file is usually the right place.

But, editing your theme’s files directly can be risky. If you update your theme later, your changes might be lost. To prevent this, think about creating a child theme. A child theme is a safe space for your custom changes.

This way, you can try out code snippets without changing the main theme’s basic files.

Backup Best Practices Before Making Changes

Before you change your site’s code, like adding a new code snippet or changing an old one, make sure to create a backup! This is very important, especially with the functions.php file.

A backup gives you a safety net. It lets you return to a previous version of your site if something goes wrong with your custom code. You can back up your whole WordPress website, which includes your database and files, or just back up your theme’s files.

Many hosting providers make it easy to back up your site. You can also use a plugin for more control over your backups.

Troubleshooting Common Issues with Custom Code Snippets

Even skilled developers sometimes run into problems. When using code snippets, things may not go as you expected. But don’t worry!

We will share some tips and strategies for debugging to help you deal with those surprises.

Debugging Tips for Identifying and Fixing Code Errors

Code errors can stop your WordPress site from working. It is important to learn how to debug your code to find and fix these problems. Begin by looking closely at your code for typos, missing semicolons, or wrong syntax.

You can also use online code validators. Turning on WordPress debug mode can give you useful error messages. Testing your code in a staging environment is a good idea. This way, you can avoid messing up your live site.

How to Ensure Compatibility with WordPress Updates

WordPress keeps changing and improving. New updates come out often. It is important to make sure that any custom code you add to your site works well with these updates.

Before you upgrade WordPress or any themes or plugins, test them carefully in a safe environment first. This helps you to find any problems. Keep your custom code organized and write clear notes in it. This will make future updates and fixing issues simpler.

Conclusion

In conclusion, using code snippets on your WordPress website can greatly improve how it works and performs. You can start with simple things like removing scripts you don’t use. You can also try advanced changes such as boosting your SEO and security. These code snippets bring many perks. But it is important to follow good practices when adding them. This means you should back up your site first and know how to use the functions.php file. If you use code snippets wisely, you can make your website’s user experience better and improve many tasks. Try out code snippets to realize the full power of your WordPress site!

Frequently Asked Questions

How do I add code snippets to WordPress without a plugin?

You can add PHP code snippets right into your theme’s functions.php file or other theme files. But using a WordPress code snippet plugin is a better choice. It gives you a more organized and easier experience.

What is the safest way to test new code snippets on my site?

The best way to test code is in a staging environment. This is like a copy of your live site. It lets you try out things without putting your live site at risk. You can safely test, fix, and improve your code here before it goes live.

Can custom code snippets slow down my WordPress website?

Poorly written custom code or too many plugins can slow down a website. On the other hand, code that is well-optimized can improve how the website works without causing any major slowdowns.

FREE SEO-ready websites

Premade SEO-optimized websites for WordPress.

Free e-commerce digital products website template. Digital products e-commerce store for Woocommerce.
Free e-commerce digital products website template. Digital products e-commerce store for Woocommerce.

FREE SEO-ready websites

Continue Learning

Find related topics.

Start With a Free SEO-ready website

A collection of SEO-optimized websites that will save you time, money, and set you in the right direction.

SEO Services Landing Page website template

The Menu

Where would you like to go from here?

help premade websites premadewebsites.co