Home » Web Tutorials » WordPress » 25 Useful WordPress functions.php Code Snippets and Tricks

25 Useful WordPress functions.php Code Snippets and Tricks

The functions.php file is one of the most useful files in a WordPress theme. It allows you to customize your website, add new functionality, modify existing features, and control different aspects of WordPress without installing additional plugins. In this article, we will look at 25 useful WordPress code snippets that you can add to the functions.php file to customize your website.

How to Add Code Snippets to functions.php?

You can find the file inside your active WordPress theme directory wp-content/themes/your-theme/functions.php. There are several ways to edit this file:

  • WordPress Theme File Editor: Go to “Appearance > Theme File Editor” and select your active theme’s functions.php file.
  • Hosting File Manager: Open File Manager app in hosting control panel, navigate to the theme directory, and edit functions.php.
  • FTP Client: Connect to your website using an FTP client like FileZilla and download the file for editing.
  • Code Snippet Plugin: Use a plugin to add PHP snippets without directly modifying theme files.

The following snippets are designed to be added individually at the end of the file. Do not add another <?php opening tag if the file already contains one.

Important: Before making changes, back up your website and the original functions.php file. Prefer adding custom code to a child theme so that theme updates do not overwrite your changes.

1. Disable WordPress Emojis

WordPress loads emoji related JavaScript and CSS to support emoji rendering across browsers. If you do not need this functionality, you can remove the associated scripts and styles using the following code.

function disable_wordpress_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_action( 'init', 'disable_wordpress_emojis' );

This removes WordPress’s built-in emoji detection scripts and styles. It does not prevent visitors from using their device’s native emoji in comments and contact forms.

2. Disable WordPress RSS Feeds

RSS feeds allow visitors and applications to subscribe to your website’s content. If you do not use RSS feeds, you can disable them.

function disable_wordpress_rss_feeds() {
    wp_die(
        'RSS feeds are disabled on this website.',
        'RSS Feeds Disabled',
        array( 'response' => 404 )
    );
}

add_action( 'do_feed', 'disable_wordpress_rss_feeds', 1 );
add_action( 'do_feed_rdf', 'disable_wordpress_rss_feeds', 1 );
add_action( 'do_feed_rss', 'disable_wordpress_rss_feeds', 1 );
add_action( 'do_feed_rss2', 'disable_wordpress_rss_feeds', 1 );
add_action( 'do_feed_atom', 'disable_wordpress_rss_feeds', 1 );
add_action( 'do_feed_rss2_comments', 'disable_wordpress_rss_feeds', 1 );
add_action( 'do_feed_atom_comments', 'disable_wordpress_rss_feeds', 1 );

This prevents WordPress from generating its standard RSS, RDF, and Atom feeds. Only use this snippet if your website does not depend on RSS subscriptions or feed-based integrations.

3. Remove WordPress Version Number

WordPress automatically adds its version number to the website’s HTML source code. The below code removes the generator meta tag that identifies the WordPress version using a simple filter.

function remove_wordpress_version() {
    return '';
}
add_filter( 'the_generator', 'remove_wordpress_version' );

Note that it does not hide the version from every possible location or provide comprehensive security protection.

4. Disable Gutenberg Block Editor

If you prefer the Classic Editor, you can disable the Gutenberg block editor for standard posts and pages.

function disable_gutenberg_editor( $use_block_editor, $post_type ) {
    if ( in_array( $post_type, array( 'post', 'page' ), true ) ) {
        return false;
    }

    return $use_block_editor;
}
add_filter( 'use_block_editor_for_post_type', 'disable_gutenberg_editor', 10, 2 );

This switches posts and pages to the classic editing experience while leaving other post types unchanged.

5. Disable Comments

If you run a website that does not accept visitor comments, you can disable the comment and ping features for all post types.

function disable_all_wordpress_comments() {
    foreach ( get_post_types() as $post_type ) {
        if ( post_type_supports( $post_type, 'comments' ) ) {
            remove_post_type_support( $post_type, 'comments' );
        }

        if ( post_type_supports( $post_type, 'trackbacks' ) ) {
            remove_post_type_support( $post_type, 'trackbacks' );
        }
    }
}
add_action( 'admin_init', 'disable_all_wordpress_comments' );

add_filter( 'comments_open', '__return_false', 20, 2 );
add_filter( 'pings_open', '__return_false', 20, 2 );

This disables new comments and trackbacks and removes the corresponding post type support in the administration area. Existing comments are not deleted.

Note: If you only use the default posts, you can go to “Settings > Discussion” and disable commenting. Alternatively, you can disable commenting for individual posts when editing its content in Gutenberg or Classic Editor.

6. Remove Comments URL Field

If you want to keep the comment feature but remove the website URL field from the comment form, use this snippet.

function remove_comment_url_field( $fields ) {
    unset( $fields['url'] );
    return $fields;
}
add_filter( 'comment_form_default_fields', 'remove_comment_url_field' );

This removes the website URL field while keeping the name, email, and comment fields available.

Website URL Removed in Comments Form
Website URL Removed in Comments Form

7. Add Custom Excerpt Length

WordPress uses a default excerpt length of approximately 55 words. You can change this length to suit your website design. For example, the following code changes the excerpt length to 30 words.

function custom_excerpt_length( $length ) {
    return 30;
}
add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );

Change 30 to any word count you prefer.

8. Change Excerpt Ending

By default, WordPress adds an ellipsis at the end of an automatically generated excerpt. You can replace it with custom text.

function custom_excerpt_ending( $more ) {
    return '... Read More';
}
add_filter( 'excerpt_more', 'custom_excerpt_ending' );

You can replace ... Read More with any text you want. This changes the excerpt ending but does not automatically create a clickable Read More link.

9. Add Featured Images Support

If your WordPress theme does not support featured images, you can enable this functionality using functions.php.

function enable_featured_images() {
    add_theme_support( 'post-thumbnails' );
}
add_action( 'after_setup_theme', 'enable_featured_images' );

After adding the code, WordPress will provide the “Featured Image” option in the post and page editor. If your theme already supports featured images, you do not need this snippet.

10. Add Custom Image Sizes

WordPress generates several image sizes when you upload an image (which also depends on your theme). You can register additional sizes for your website. For example, the following code creates a custom image size of 800 × 450 pixels.

function add_custom_wordpress_image_sizes() {
    add_image_size( 'custom-thumbnail', 800, 450, true );
}
add_action( 'after_setup_theme', 'add_custom_wordpress_image_sizes' );

You can display the registered image size in your theme using:

the_post_thumbnail( 'custom-thumbnail' );

The third argument, true, enables hard cropping.

Note: WordPress generates the new size for future uploads. Existing images may require thumbnail regeneration.

11. Redirect Users After Login

You can redirect users to a specific page after they successfully log in to WordPress. For example, the following code redirects users to the website homepage.

function custom_login_redirect( $redirect_to, $requested_redirect_to, $user ) {
    if ( ! is_wp_error( $user ) && $user instanceof WP_User ) {
        return home_url( '/' );
    }

    return $redirect_to;
}
add_filter( 'login_redirect', 'custom_login_redirect', 10, 3 );

Change home_url( '/' ) to another destination if you want users to land on a particular page. This applies to all successfully authenticated users. If you use membership or ecommerce plugins, consider their own redirect settings before applying a global redirect.

12. Redirect Users After Logout

You can also control where users land after logging out of WordPress. The following snippet redirects visitors to the homepage after logout.

function custom_logout_redirect() {
    return home_url( '/' );
}
add_filter( 'logout_redirect', 'custom_logout_redirect', 10, 3 );

You can replace the homepage URL with a custom login page or another destination.

13. Redirect 404 Pages to Homepage

A 404 error appears when WordPress cannot find the requested page. If you want to redirect all 404 pages to your homepage, use this code.

function redirect_404_to_homepage() {
    if ( is_404() ) {
        wp_safe_redirect( home_url( '/' ), 301 );
        exit;
    }
}
add_action( 'template_redirect', 'redirect_404_to_homepage' );

This sends a permanent redirect for every missing page.

Note: Redirecting every 404 URL to the homepage is generally not recommended. It can create soft 404 issues. For better SEO, redirect individual URLs to their most relevant replacement pages or retain genuine 404 responses.

14. Add Custom Login Logo

You can replace the default WordPress logo on the login page with your own website logo. Add this code:

function custom_wordpress_login_logo() {
    ?>
    <style>
        #login h1 a {
            background-image: url('https://example.com/logo.png');
            background-size: contain;
            background-position: center;
            width: 100%;
            height: 80px;
        }
    </style>
    <?php
}
add_action( 'login_enqueue_scripts', 'custom_wordpress_login_logo' );

Replace https://example.com/logo.png with the URL of your own logo. You can adjust the width and height to match your image dimensions. Below is how the default and custom logos look on the login page.

Default Login Logo in WordPress
Default Login Logo in WordPress
Login Page with Custom Logo
Login Page with Custom Logo

15. Change Login Logo URL

By default, clicking the WordPress login logo takes visitors to WordPress.org. You can change this to point to your website.

function custom_login_logo_url() {
    return home_url( '/' );
}
add_filter( 'login_headerurl', 'custom_login_logo_url' );

You can also change the logo’s hover title:

function custom_login_logo_title() {
    return get_bloginfo( 'name' );
}
add_filter( 'login_headertext', 'custom_login_logo_title' );

This makes the login page more consistent with your website branding.

16. Add Custom Dashboard Footer Text

WordPress displays default text in the administration dashboard footer. You can replace it with your own message.

function custom_admin_footer_text() {
    return 'Thank you for managing your website!';
}
add_filter( 'admin_footer_text', 'custom_admin_footer_text' );

You can replace the message with your website name, support information, or another custom message.

17. Disable XML-RPC

XML-RPC is a WordPress feature that allows external applications to communicate with your website. If you do not use XML-RPC, you can disable it using the following code.

add_filter( 'xmlrpc_enabled', '__return_false' );

This disables XML-RPC authentication through the standard WordPress setting. If you use an application or service that depends on XML-RPC, such as certain remote publishing integrations, check compatibility before disabling it.

18. Disable REST API for Logged Out Users

WordPress provides a REST API that allows applications and services to access website data. If you want to restrict REST API requests to logged in users, use this snippet.

function restrict_rest_api_for_guests( $result ) {
    if ( ! empty( $result ) ) {
        return $result;
    }

    if ( ! is_user_logged_in() ) {
        return new WP_Error(
            'rest_not_logged_in',
            'You must be logged in to access the REST API.',
            array( 'status' => 401 )
        );
    }

    return $result;
}
add_filter( 'rest_authentication_errors', 'restrict_rest_api_for_guests' );

This blocks unauthenticated REST API requests, including requests to endpoints that may otherwise be publicly accessible. Be careful when using this snippet as it can break the block editor, public integrations, and plugins that depend on public REST API access.

19. Remove WordPress Admin Bar

WordPress displays an administration toolbar at the top of the website when logged in users visit the frontend. You can hide this toolbar for all users using the following code.

add_filter( 'show_admin_bar', '__return_false' );

This hides the frontend admin bar but does not remove access to the WordPress dashboard.

Note: Users can also go to “Users > Profile” section and uncheck “Show Toolbar when viewing site” option to hide the toolbar.

20. Add Custom Body Classes

WordPress automatically adds CSS classes to the HTML body element. You can add your own classes to customize the appearance of individual pages. For example, the following code adds a custom class to the homepage.

function add_custom_body_classes( $classes ) {
    if ( is_front_page() ) {
        $classes[] = 'custom-homepage';
    }

    return $classes;
}
add_filter( 'body_class', 'add_custom_body_classes' );

You can then use the class in your theme’s CSS:

.custom-homepage {
    background-color: #f5f5f5;
}

You can modify the condition to add classes to specific posts, pages, categories, or other templates.

21. Remove Unused Dashboard Widgets

WordPress displays several widgets on the administration dashboard. If you do not need them, you can remove selected widgets to simplify the dashboard.

function remove_wordpress_dashboard_widgets() {
    remove_meta_box( 'dashboard_primary', 'dashboard', 'side' );
    remove_meta_box( 'dashboard_quick_press', 'dashboard', 'side' );
    remove_meta_box( 'dashboard_activity', 'dashboard', 'normal' );
    remove_meta_box( 'dashboard_site_health', 'dashboard', 'normal' );
}
add_action( 'wp_dashboard_setup', 'remove_wordpress_dashboard_widgets' );

This removes selected default dashboard widgets, including WordPress news, Quick Draft, Activity, and Site Health. You can add more remove_meta_box() statements to remove other dashboard widgets.

Note: The above code permanently removes the widgets. If you simply want to hide the widgets, click the “Screen Options” button on top right corner and uncheck the items that you want to hide.

22. Change WordPress Search to Search Titles Only

By default, WordPress searches post content and other supported fields. If you want search results to match only post titles, you can modify the search query.

function search_only_post_titles( $query ) {
    if ( ! is_admin() && $query->is_main_query() && $query->is_search() ) {
        $query->set( 'search_columns', array( 'post_title' ) );
    }
}
add_action( 'pre_get_posts', 'search_only_post_titles' );

This uses the search_columns query parameter available in WordPress 6.2 and later. It affects the main frontend search query. Other search queries and custom search implementations may need separate configuration.

23. Exclude Categories from WordPress Search

If you want to prevent posts from selected categories from appearing in WordPress search results, use the following code.

function exclude_categories_from_search( $query ) {
    if ( ! is_admin() && $query->is_main_query() && $query->is_search() ) {
        $query->set( 'category__not_in', array( 5, 10 ) );
    }
}
add_action( 'pre_get_posts', 'exclude_categories_from_search' );

Replace 5 and 10 with the category IDs you want to exclude. This snippet affects the main frontend search query.

Note: You can find category IDs by opening “Posts > Categories” and checking the category edit URL.

24. Disable Automatic Updates

WordPress can automatically install certain updates to keep websites current. If you prefer to manage updates manually, you can disable the automatic updater.

add_filter( 'automatic_updater_disabled', '__return_true' );

This disables the WordPress automatic updater, including automatic core, plugin, and theme updates handled by that system. It does not prevent manually initiated updates. Remember that disabling automatic updates means you must regularly check for security patches and install important updates yourself.

25. Add Custom CSS to WordPress Admin

You can easily add custom CSS for individual blocks and site-wide CSS in WordPress. You can also customize the administrator dashboard without editing the original admin stylesheets. For example, the following snippet changes the dashboard background color.

function add_custom_admin_css() {
    $css = '
        body.wp-admin {
            background-color: #f5f5f5;
        }

        #wpadminbar {
            background-color: #222222;
        }
    ';

    wp_add_inline_style( 'common', $css );
}
add_action( 'admin_enqueue_scripts', 'add_custom_admin_css' );

You can modify the CSS to change dashboard colors, fonts, spacing, and other visual elements.

Conclusion

The WordPress functions.php file provides a convenient way to customize your website without installing a separate plugin for every small requirement. With these 25 code snippets, you can control comments, modify the login page, customize excerpts, manage image sizes, change search behavior, simplify the dashboard, and adjust several other WordPress features. Always back up your files before editing and test custom code carefully. For frequently used customizations, consider creating a functional plugin so your code remains independent of the active theme.

Leave a Comment

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