Back

Most useful code snippets for WordPress function file.

Diving straight into the heart of website customization, the functions.php file holds the key to many tweaks and enhancements. But with endless possibilities, where does one start? In this blog post, we’re spotlighting 30 invaluable code snippets tailored for this very file. These aren’t just any snippets; they’re handpicked for their utility and impact, designed to provide quick solutions and elevate your site’s functionality. Whether you’re a seasoned developer or just getting your feet wet, these code gems are here to make your life a tad bit easier. So, before we journey further, ensure you’ve backed up your site, and let’s get coding!

1. Allow SVG uploads in WordPress

WordPress, by default, doesn’t allow SVG file uploads for security reasons, as SVG files can contain malicious code. However, if you need to upload SVG files, there are ways to enable this functionality. Always make sure the SVG files you’re uploading are from trusted sources.

function add_svg_mime_type( $mimes ) {
    $mimes['svg'] = 'image/svg+xml';
    return $mimes;
}

add_filter('upload_mimes', 'add_svg_mime_type');

2. Hide WordPress Version

Hiding the WordPress version can be a part of hardening your WordPress installation, making it a little bit harder for attackers to exploit known vulnerabilities associated with specific WordPress versions.

function remove_wp_version() {
    return '';
}

add_filter('the_generator', 'remove_wp_version');

Remember, security through obscurity (like hiding the version number) isn’t a foolproof method, but it’s an additional layer that can be combined with other security measures for a more comprehensive approach.

3. Limit posts revisions

Post revisions are a useful feature in WordPress, allowing you to go back to previous versions of your posts. However, if you have numerous revisions, it can take up a considerable amount of database space. Limiting the number of post revisions can help manage database bloat.

The most common way to set a limit to post revisions is by editing the wp-config.php file. You can find this file in the root directory of your WordPress installation.

define('WP_POST_REVISIONS', 5);

In the example above, the number 5 indicates the maximum number of revisions WordPress should keep for each post. You can change this number to any other value based on your preference.

If you want to completely disable post revisions, you can set the value to false:

define('WP_POST_REVISIONS', false);

4. Add custom WordPress Dashboard logo

Adding a custom logo to your WordPress dashboard can provide a more branded experience for you and other users of the website. Here’s how you can add a custom logo to the WordPress dashboard:

function custom_admin_logo() {
    echo '<style type="text/css">
        #wpadminbar #wp-admin-bar-wp-logo > .ab-item .ab-icon:before {
            background-image: url(' . get_stylesheet_directory_uri() . '/images/your-logo.png) !important;
            background-size: cover;
            color:rgba(0, 0, 0, 0);
        }
        #wpadminbar #wp-admin-bar-wp-logo:hover > .ab-item .ab-icon {
            background-position: 0 0;
        }
    </style>';
}

add_action('admin_head', 'custom_admin_logo');

5. Change the default “Read More” text

Every WordPress website uses the “Read More” link to tease content and invite visitors to dive deeper into articles. While it’s an established convention, there might be times you wish to customize it to better fit your site’s voice or theme. Whether you want to make it more enticing, descriptive, or align it with your brand’s language, changing this default text can make a difference. In this guide, we’ll walk you through the simple steps to customize the “Read More” text in your WordPress website.

function custom_read_more_link() {
    return ' <a href="' . get_permalink() . '">Custom Read More...</a>';
}
add_filter('the_content_more_link', 'custom_read_more_link');

6. Remove the admin bar for all users.

The WordPress admin bar offers quick access to administrative functions right from the frontend of your website. While it’s handy for website administrators, there might be instances when you want a cleaner view for all users, including admins. Disabling this bar can enhance user experience and streamline your website’s appearance.

add_filter('show_admin_bar', '__return_false');

7. Add a custom image size.

Every website has its unique visual language and layout needs. While WordPress comes with predefined image sizes, there are occasions when they just don’t fit the bill.

add_image_size('custom-size', 600, 400, true);

8.Change the default gravatar.

Gravatars, or “Globally Recognized Avatars,” are the small images that represent users across the WordPress ecosystem. By default, WordPress assigns a standard image for users without a custom Gravatar. But what if you want to add a personal touch or ensure brand consistency?

add_filter('avatar_defaults', 'new_default_avatar');

function new_default_avatar($avatar_defaults) {
    $avatar_defaults['http://example.com/path/to/image.jpg'] = 'Custom Avatar Name';
    return $avatar_defaults;
}

9. Change the length of excerpts.

Excerpts in WordPress are concise previews of your content, offering readers a quick glimpse into the full post. While the default length might be suitable for some, your site’s design or content strategy might demand a different size. Tailoring the length of these previews can significantly impact user engagement and page aesthetics.

function custom_excerpt_length($length) {
    return 20; // Number of words
}

add_filter('excerpt_length', 'custom_excerpt_length', 999);

10. Redirect users after login based on role.

In a diverse WordPress environment, different user roles mean different responsibilities and areas of interest. Wouldn’t it be efficient if, upon login, users are directed to pages that are most relevant to their roles? Customizing the post-login redirect based on roles can enhance user experience and streamline site management.

function redirect_user_on_role() {
    global $current_user;
    get_currentuserinfo();
    if (in_array('subscriber', $current_user->roles)) {
        wp_redirect('http://example.com/');
        exit;
    }
}

add_action('admin_init', 'redirect_user_on_role');

11. Disallow file editing from the dashboard.

The ability to edit theme and plugin files directly from the WordPress dashboard can be a double-edged sword. While it offers convenience, it also poses security risks and can lead to inadvertent mistakes that disrupt site functionality. To enhance your site’s security and reduce potential errors, you might consider disabling file editing from the dashboard.

define('DISALLOW_FILE_EDIT', true);

12. Set a custom admin footer text.

The admin dashboard is the nerve center of your WordPress website. While its primary role is functional, adding a touch of personalization can enhance the experience for site managers and contributors. One subtle yet effective tweak is customizing the admin footer text. Whether you want to add copyright information, a personal note, or branding elements, changing this text can make a difference.

function custom_admin_footer() {
    echo 'Your custom text here.';
}

add_filter('admin_footer_text', 'custom_admin_footer');

13. Add custom CSS to the WordPress admin area.

While the frontend of your WordPress website is the main showcase for visitors, the admin area is where all the backend action happens. Tweaking its appearance to align with your branding or to improve readability can be a worthwhile enhancement for those who manage the site regularly. Injecting custom CSS into the admin area offers you this flexibility.

function custom_admin_css() {
    echo '<style>
       /* Your CSS code here */
    </style>';
}

add_action('admin_head', 'custom_admin_css');

14. Change the default sender name and email for WordPress emails.

By default, WordPress sends emails using a generic sender name like “WordPress” with an email address like “wordpress@yourdomain.com“. While this works, it may not resonate with your brand’s identity or may look impersonal to recipients. Personalizing the sender’s details can foster better trust and open rates.

function custom_wordpress_from_name($email) {
    return 'Your Name';
}

function custom_wordpress_from_email($email) {
    return 'you@example.com';
}
add_filter('wp_mail_from_name', 'custom_wordpress_from_name');

add_filter('wp_mail_from', 'custom_wordpress_from_email');

15. Add a shortcode to display the current year.

Implement a simple shortcode that will always display the current year, ensuring your content remains up-to-date.

function current_year_shortcode() {
    return date('Y');
}

add_shortcode('year', 'current_year_shortcode');

16. Remove unwanted items from the admin bar.

By removing unwanted items from the admin bar, you can create a cleaner, more focused working environment.

function remove_from_admin_bar($wp_admin_bar) {
    $wp_admin_bar->remove_node('wp-logo');
}

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

17. Change the default “Howdy” message in the admin bar.

The familiar “Howdy” greeting in the WordPress admin bar has been a longstanding tradition. Yet, sometimes, a more personalized or brand-centric message might better resonate with your website’s ethos or your users.

function replace_howdy_message($wp_admin_bar) {
    $my_account = $wp_admin_bar->get_node('my-account');
    $new_title = str_replace('Howdy,', 'Welcome,', $my_account->title);
    $wp_admin_bar->add_node(array(
        'id' => 'my-account',
        'title' => $new_title,
    ));
}

add_filter('admin_bar_menu', 'replace_howdy_message', 25);

18. Disable Code Editing in Block Editor.

For enhanced security and consistency, you might consider disabling code editing within the Block Editor.

add_filter( 'block_editor_settings_all', function ( $settings ) {
     
    $settings['codeEditingEnabled'] = current_user_can( 'manage_options' );
 
    return $settings;
} );
Back

WordPress tutorial – AJAX based login and registration modal without using a plugin.

Creating an AJAX-based registration and login modal for your WordPress website can significantly improve user experience by providing a seamless login and registration process. In this tutorial, we’ll guide you through the steps to create a custom login and registration modal without using a plugin. By the end of this tutorial, you’ll have a fully functioning AJAX-based login and registration system for your WordPress site.

Prerequisites:

Step 1

Create Custom Login and Registration Forms First, we need to create the login and registration forms using HTML. Place the following code in your theme’s template file where you want the login and registration modals to appear.

<!-- Login Form -->
<div id="ajax-login-form">
    <h3>Login</h3>
    <form id="login-form">
        <input type="text" id="login-username" placeholder="Username">
        <input type="password" id="login-password" placeholder="Password">
        <button type="button" id="login-submit">Login</button>
    </form>
    <div id="login-message"></div>
</div>

<!-- Registration Form -->
<div id="ajax-register-form">
    <h3>Register</h3>
    <form id="register-form">
        <input type="text" id="register-username" placeholder="Username">
        <input type="email" id="register-email" placeholder="Email">
        <input type="password" id="register-password" placeholder="Password">
        <button type="button" id="register-submit">Register</button>
    </form>
    <div id="register-message"></div>
</div>

Step 2

Enqueue JavaScript and CSS Files Next, add the following code to your theme’s functions.php file to enqueue the necessary JavaScript and CSS files.

function enqueue_ajax_auth_scripts() {
    wp_enqueue_script('ajax-auth-script', get_template_directory_uri() . '/ajax-auth.js', array('jquery'), null, true);
    wp_localize_script('ajax-auth-script', 'ajax_auth_object', array(
        'ajaxurl' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('ajax-auth-nonce'),
    ));
}
add_action('wp_enqueue_scripts', 'enqueue_ajax_auth_scripts');

Step 3

Create a JavaScript File for AJAX Functionality Create a new JavaScript file called ajax-auth.js in your theme directory and add the following code:

jQuery(document).ready(function ($) {
    // Login AJAX
    $('#login-submit').on('click', function () {
        var data = {
            action: 'ajax_login',
            security: ajax_auth_object.nonce,
            username: $('#login-username').val(),
            password: $('#login-password').val(),
        };

        $.post(ajax_auth_object.ajaxurl, data, function (response) {
            var result = JSON.parse(response);
            $('#login-message').html(result.message);

            if (result.loggedin) {
                location.reload();
            }
        });
    });

    // Register AJAX
    $('#register-submit').on('click', function () {
        var data = {
            action: 'ajax_register',
            security: ajax_auth_object.nonce,
            username: $('#register-username').val(),
            email: $('#register-email').val(),
            password: $('#register-password').val(),
        };

        $.post(ajax_auth_object.ajaxurl, data, function (response) {
            var result = JSON.parse(response);
            $('#register-message').html(result.message);

            if (result.registered) {
                location.reload();
            }
        });
    });
});

Step 4

Add AJAX Handlers and PHP Functions for Login and Registration Add the following code to your theme’s `functions.php` file to create AJAX handlers and PHP functions for handling login and registration.

// AJAX Handlers
add_action('wp_ajax_nopriv_ajax_login', 'ajax_login');
add_action('wp_ajax_nopriv_ajax_register', 'ajax_register');

// Login Function
function ajax_login() {
    check_ajax_referer('ajax-auth-nonce', 'security');
    $username = $_POST['username'];
    $password = $_POST['password'];

    $user = wp_authenticate($username, $password);

    if (is_wp_error($user)) {
        echo json_encode(array('loggedin' => false, 'message' => 'Invalid username or password.'));
    } else {
        wp_set_current_user($user->ID);
        wp_set_auth_cookie($user->ID);
        echo json_encode(array('loggedin' => true, 'message' => 'Login successful.'));
    }
    die();
}

// Registration Function
function ajax_register() {
    check_ajax_referer('ajax-auth-nonce', 'security');
    $username = $_POST['username'];
    $email = $_POST['email'];
    $password = $_POST['password'];

    $user_data = array(
        'user_login' => $username,
        'user_email' => $email,
        'user_pass' => $password,
    );

    $user_id = wp_insert_user($user_data);

    if (is_wp_error($user_id)) {
        echo json_encode(array('registered' => false, 'message' => $user_id->get_error_message()));
    } else {
        echo json_encode(array('registered' => true, 'message' => 'Registration successful.'));
    }
    die();
}

Conclusion

You have now successfully created an AJAX-based registration and login modal for your WordPress website. This custom solution will provide a seamless login and registration process for your users without relying on a plugin. You can further customize the appearance and functionality of the modal to better fit your website’s design and requirements.