WordPress functions.php Hacks

WordPress functions.php file is where you add all functionality of your WordPress theme. If you are developing or modifying a WordPress theme then you should have full command of WordPress functions.php file.

What is WordPress functions.php file?

WordPress functions.php file acts as a plugin within your WordPress theme and gets loaded when you activate a theme.

Usually, you define classes, functions, action and action filters in this file. You can add extra features to your WordPress theme or extend the functionality of WordPress using this file.

The WordPress Codex defines the functions.php file as

The functions file behaves like a WordPress Plugin, adding features and functionality to a WordPress site through PHP code. You can use it to call native PHP functions, WordPress functions, or to define your own functions.

By default, all WordPress themes, free or paid, comes with a functions.php file which adds extra functionality to that themes.

It’s important to differentiate between a plugin and functions.php purpose. Honestly, you can add all plugin functionality to a functions.php file which will end up with a huge file and hard to manage.

In my views, we should only include theme-specific functionality in the functions.php file and any stand-alone feature should be separated as a plugin.

Today I will show you how you can extend WordPress to add extra features to your theme by using a functions.php file.

Creating a functions.php file

First thing first, you should have access to your website root directory by using FTP Client. FTP to your website root and find /wp-content/themes/your-theme folder. If you have functions.php file, download it and save it as a backup copy. If you don’t have a functions.php file then create a new file in the theme’s main directory and call it functions.php.

If you have just created a new file (functions.php) then you will need to add a PHP opening tag like below and don’t add a closing tag in the file.

<?php

I always add a comment block in my code files with the most relevant description of the code, so I can find the code again easily. See below.

<?php
/************************************************************************
        Functions.php File : Theme Specific Features
************************************************************************/

1. Adding Theme Support

When you create a new WordPress theme, some features will not be available to your theme, for those you have to add support for your theme such as different post formats, title tags, HTML5 support, custom background etc.

To add support for different post types, we will use WordPress’s function add_theme_support(). Add the code to your functions.php file to add support for post types.

/************************************************************************
                        Add Theme Support Functions
************************************************************************/
    add_theme_support( 'post-formats' );

You can pass extra parameters to add_theme_support() function to declare which posts types you want to add to your theme.

/************************************************************************
                        Add Theme Support Functions
************************************************************************/
    add_theme_support( 'post-formats' , 'video', 'quote');

To add featured image support for post types you can use the code below.

/************************************************************************
                        Add Theme Support Functions
************************************************************************/
    add_theme_support( 'post-thumbnails', array( 'post', 'page', 'quote'));

None of the above code will work until we call above code inside a hook. I will place all theme support functions inside another function and then pass that function to action hook called likeafter_setup_theme below.

/************************************************************************
                        Add Theme Support Functions
************************************************************************/
    function rukhsar_add_theme_support() {
        // Post Formats
        add_theme_support( 'post-formats' , 'video', 'quote');

        // Post Feature Image
        add_theme_support( 'post-thumbnails', array( 'post', 'page', 'quote'));

        // HTML Support
        add_theme_support( 'html5' );
    }

    add_action( 'after_setup_theme', 'rukhsar_add_theme_support' );

2. Registering Navigation Menus

WordPress theme developers can register their custom menus which they can show them within their theme. You can register a menu which below code which will add a new menu location in WordPress
admin.

/************************************************************************
                        Add Custom Menu Functions
************************************************************************/
    function rukhsar_custom_new_menu() {
      register_nav_menu('rukhsar-custom-menu',__( 'My Custom Footer Menu' ));
    }
    add_action( 'init', 'rukhsar_custom_new_menu' );

If you have activated your custom theme, by adding code to your file (functions.php) you will see My Custom Footer Menu as theme location option.

Registering navigation menu in WordPress - WordPress functions.php Hacks

Registering navigation menu in WordPress

You can display your newly created menu in within your theme, by adding the following code to your template file.

/************************************************************************
                        Add Custom Menu Functions
************************************************************************/
    wp_nav_menu( array( 'theme_location' => 'rukhsar-custom-menu', 'container_class' => 'custom-menu-class' ) );

3. Remove the WordPress Version Number

By default, WordPress shows version number on your site and in the WordPress admin area. You might want to remove the version number from your site.

WordPress Version Number Generator - WordPress functions.php Hacks

WordPress Version Number Generator

Simply add the following code in your functions.php file and WordPress version number will be removed from the site.

/************************************************************************
                    Remove WordPress Version Number
************************************************************************/
        function rukhsar_remove_version() {
            return '';
        }
        add_filter('the_generator', 'rukhsar_remove_version');

4. Change the Footer in WordPress Admin Panel

You might have seen Thank you for creating with WordPress message in WordPress admin area and want to remove it. Use the following code and default WordPress message will be replaced by what you supply in below code snippet.

/************************************************************************
                Change the Footer in WordPress Admin Panel
************************************************************************/
        function rukhsar_remove_footer_admin() {
            echo 'Built by <a href="https://www.rukhsar.me.uk">Rukhsar Manzoor</a>';
        }
        add_filter('admin_footer_text', 'rukhsar_remove_footer_admin');

5. Add Custom Dashboard Widgets in WordPress

You might have seen some third party widgets when you use a premium or free theme. WordPress enables developers to add custom widgets to WordPress dashboard.

You can add whatever you want to in that widget. By using below simple code snippet you can add a custom widget to WordPress dashboard.

/************************************************************************
            Add Custom Dashboard Widgets in WordPress
************************************************************************/
        function rukhsar_dashboard_help() {
            echo 'Welcome to my custom widget';
        }

        add_action('wp_dashboard_setup', 'rukhsar_custom_widget');

        function rukhsar_custom_widget() {
            global $wp_meta_boxes;
            wp_add_dashboard_widget('rukhsar_dashboard_help', 'Theme Support', 'rukhsar_dashboard_help');
        }
Add dashboard widget to WordPress to admin area - WordPress functions.php Hacks

Add dashboard widget to WordPress to the admin area

6. Update WordPress URLs

You might be in a situation when you can not access WordPress admin area, one reason for that will be you have to update WordPress URLs.

You can fix this by adding the following code in functions.php file without interacting database directly.

/************************************************************************
                        Update WordPress URLs
************************************************************************/
        update_option( 'siteurl', 'http://example.com' );
        update_option( 'home', 'http://example.com' );

Once you are logged in, you can go to Settings and set the URLs there. After that you should remove the code you added to the functions file, otherwise, it will keep updating those URLs any time your site is accessed.

7. Add Additional Image Sizes in WordPress

WordPress automatically create different sizes of an image when you upload one. You can change those sizes in Settings -> Media -> Image sizes. WordPress theme developers can create extra sizes of images depending on their theme layout needs. Use below code snippet to add additional image sizes to WordPress.

/************************************************************************
                Add Additional Image Sizes in WordPress
************************************************************************/
        add_image_size( 'grid-small', 200, 200, true );
        add_image_size( 'grid-big', 400, 400 );

Above code snippet will add two image sizes one for small grid image and one for big. You can display an image size in anywhere in your theme using this code.

the_post_thumbnail( 'grid-big' );

8. Add Author Profile Fields

You can add extra filed to author profile page by adding the following code snippet in functions.php file.

/************************************************************************
                Add Author Profile Fields
************************************************************************/
        function rukhsar_job_title_field($fileds) {
            $fields['job_title'] = 'Web Developer';
            return $fields;
        }
        add_filter('author_job_title_field', 'rukhsar_job_title_field', 10, 1);

You can display job title field in your template files using the code below.

echo $author->job_title;

9. Adding Widget Ready Areas or Sidebar in WordPress Themes

Widget areas or Sidebars are very popular features of WordPress and part of most of the themes. WordPress provides a convenient way to add widget areas or sidebars to your themes.

To show widgets in your theme you have to create a custom sidebar or widget area where you can drop your widgets. WordPress theme developers can create custom widget areas using function.php file.

Add below code in your functions.php file.

/************************************************************************
                    Add Widget Area or Sidebar
************************************************************************/
    <?php
        function rukhsar_custom_sidebar() {

            $args = array(
                'id'            =>  'rukhsar_sidebar',
                'name'          =>  __( 'Custom Widget Area', 'text_domain' ),
                'description'   =>  __( 'A custom widget area for our theme', 'text_domain' ),
                'before_title'  =>  '<h3 class="widget-title">',
                'after_title'   =>  '</h3>',
                'before_widget' =>  '<aside id="%1$s" class="widget %2$s">',
                'after_widget'  =>  '</aside>',
            );
            register_sidebar( $args );
        }
        add_action('widgets_init', 'rukhsar_custom_sidebar');
    ?>

Now if you visit Appearance -> Widgets page and you will see your own custom widget area like below.

Adding custom widget or sidebar area to WordPress - WordPress functions.php Hacks

Adding a custom widget or sidebar area to WordPress

You can display custom widget area in your theme template file like below.


    <?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('rukhsar_custom_sidebar') ) : ?>
        // Sidebar content goes here
    <?php endif; ?>

10. Hide Login Errors in WordPress

You can login to WordPress admin area using a username or email address. Login errors can be used by hackers to guess what input they have to enter to bypass login page. By hiding login errors you can make your WordPress admin area a bit more secure.

/************************************************************************
                        Hide Login Error
************************************************************************/
    <?php
        function no_wordpress_errors() {
          return 'Something is wrong!';
        }
        add_filter( 'login_errors', 'no_wordpress_errors' );
    ?>

After adding above code snippet, users will see a generic login error message like below.

Hide login errors in WordPress admin - WordPress functions.php Hacks

Hide login errors in WordPress admin

11. Disable Login by Email in WordPress

WordPress provides the ability to login to WordPress admin area using an email or username. To make your WordPress installation more secure you can disable the login by email by using below code snippet in WordPress functions.php file.

/************************************************************************
                        Diable email login
************************************************************************/
    remove_filter( 'authenticate', 'wp_authenticate_email_password', 20 );

12. Change Read More Text for Excerpts

By default, WordPress adds Read More text after an excerpt of a post. You can change it to anything you want by adding the following code.

/************************************************************************
                        Change Excerpt Text
************************************************************************/
    function modify_read_more_link() {
        return '<a class="more-link" href="' . get_permalink() . '">Real Full Post</a>';
    }
    add_filter( 'the_content_more_link', 'modify_read_more_link' );

13. Change Excerpt Length in WordPress

You can change the excerpt length easily to any number of characters you want. If you want to change the default number of characters for an excerpt, then add the below code in functions.php file.

/************************************************************************
                        Change Excerpt Length
************************************************************************/
    function new_excerpt_length($length) {
        return 80;
    }
    add_filter('excerpt_length', 'new_excerpt_length');

Above code will change the number of characters to 80.

14. Add an Admin User in WordPress

You might run into a situation when you have forgotten the password of WordPress admin. Below code will create a new admin user which will solve your this problem.

/************************************************************************
                        Create Admin User
************************************************************************/
    function rukhsar_admin_account(){
        $user = 'Admin';
        $pass = 'Admin123456';
        $email = '[email protected]';
        if ( !username_exists( $user )  && !email_exists( $email ) ) {
                $user_id = wp_create_user( $user, $pass, $email );
                $user = new WP_User( $user_id );
                $user->set_role( 'administrator' );
            }
    }
    add_action('init','rukhsar_admin_account');

Replace username, password, and email to the one you want to set up. Once you have created admin user remove this code from functions.php file.

15. Remove Welcome Panel from WordPress Dashboard

You might have used the WordPress’s welcome panel on the dashboard. But for some serious users, it doesn’t add any value. You can remove it by adding the following code snippet in your functions.php file.

/************************************************************************
                    Remove Welcome Panel
************************************************************************/
    remove_action('welcome_panel', 'wp_welcome_panel');

16. Enable Shortcode in Text Widgets

WordPress’s widgets are very powerful and play a big role in forming the layout of any theme. You can not use shortcodes in WordPress’s text widget by default. You can use below piece of code to address this problem.

/************************************************************************
                Enable Shortcode for Text Widget
************************************************************************/
    add_filter('widget_text','do_shortcode');

17. Upload Additional File Types to WordPress

WordPress allows you to upload a limited number of file types. You can add additional file types support yourself (Usually done with the help of a plugin). Add the following code to your theme’s functions file.

/************************************************************************
                Additional File Types Support
************************************************************************/
    function rukhsar_myme_types($mime_types){
        $mime_types['svg'] = 'image/svg+xml'; //Adding svg extension
        $mime_types['psd'] = 'image/vnd.adobe.photoshop'; //Adding photoshop files
        return $mime_types;
    }
    add_filter('upload_mimes', 'rukhsar_myme_types', 1, 1);

You can find all mime types for the file types here and then simply use it in the code above.

18. Disable XML-RPC in WordPress

XML-RPC is a method that allows third-party apps to communicate with your WordPress site remotely. This could cause security issues and can be exploited by hackers. Simply add this code to your functions file to turn off XML-RPC in WordPress.

/************************************************************************
                Disable XML-RPC Support
************************************************************************/
    add_filter('xmlrpc_enabled', '__return_false');

19. Shortcode for Adsense

If you have enabled the Google Adsense on your WordPress site, then you might have experienced a problem with adding Adsense Ads within your Post or Page content. You can use functions.php to create your own shortcodes. Just add the following code into functions.php file and replace the specifics with your own Adsense credentials.

/************************************************************************
                 Add Adsense Shortcode
************************************************************************/
    function rukhsar_adsense_ads() {
        return '<div id="adsense"><script type="text/javascript"><!–
        google_ad_client = "pub-XXXXXXXXXXXXXX";
        google_ad_slot = "123456789";
        google_ad_width = 468;
        google_ad_height = 60;
        //–>
        </script>
        <script type="text/javascript"
        src="http://pagead2.googlesyndication.com/pagead/show_ads.js";>
        </script></div>';
    }
    add_shortcode('adsense', 'rukhsar_adsense_ads');

After adding above code you will be able to place [adsense] shortcode within your Posts or Pages.

20. Reduce/Disable Post Revisions

Revisions are a very powerful feature of WordPress but as your site grow it can slow down your WordPress website. You can reduce the number of revisions WordPress should save or completely disable them.

To tackle this issue this time we will hack WordPress’s config file to define some variables. Open your WordPress’s wp-config.php file and add below code snippet.

/************************************************************************
             Reduce / Disable WordPress Revisions
************************************************************************/
    define( 'WP_POST_REVISIONS', 3 );
    define('WP_POST_REVISIONS', false );

First line of above code snippet will limit the WordPress’s Revisions to 3. Second line will disable revisions completely. You can choose any code line according to your requirement.

21. Keep Logged in WordPress for a Longer Period

It’s always advised to log out from WordPress’s admin when you are not using especially if you have a shared working space in the office. But some users like me, wants WordPress to keep the session open for longer period. Below code will do the trick, just open functions.php file and add below.

/************************************************************************
             Increase Login Session Time
************************************************************************/
    function rukhsar_stay_logged_in( $expire ) {
        return 31556926; // 1 year in seconds
    }
    add_filter( 'auth_cookie_expiration', 'rukhsar_stay_logged_in' );

22. Change Auto-Save Interval

WordPress automatically saves your work, so you don’t have to worry about it in the event of a browser crash or a blackout. For some users though, the 1 minute default could be a little too much and they keep interrupting their work to push the save button. Add below code in your WordPress’s wp-config.php file to reduce the autosave interval.

/************************************************************************
                    Change Auto-Save Interval
************************************************************************/
    define( 'AUTOSAVE_INTERVAL', 45 );

23. Add a Favicon Using a Hook

Almost all websites have their own favicon now a days. You can edit the favicon by editing header.php file but I will share a more clean way to achieve this in your WordPress theme.

Just add the below code into your functions.php file and save it or upload it.

Nowadays, any serious blog has its own favicon. To add yours to WordPress, you can directly edit header.php or you can use a more clean technique, using the power of WordPress hooks.

/************************************************************************
                    Add Favicon using a Hook
************************************************************************/
    function custom_favicon() { ?>
    <link rel="shortcut icon" href="<?php echo get_template_directory(); ?>/images/favicon.png" >
    <?php }
    add_action('wp_head', 'custom_favicon');

Don’t forget to change the favicon URL if needed. Also, please note that if the wp_head() function haven’t been implemented in your theme, this hack will not work.

24. Insert Custom Content after each Post

You might want to display some text under each post. You can add it by editing all posts but that is a tedious job. It will be a lot easier to achieve this using WordPress hook. Add this code snippet in your functions.php file and save it. Once done, custom text will be added below each post automatically.

/************************************************************************
                Add Custom Content After Each Post
************************************************************************/
   function add_post_content($content) {
        if(!is_feed() && !is_home()) {
            $content .= '<p>This article is copyright © '.date('Y').' '.bloginfo('name').'</p>';
        }
        return $content;
    }
    add_filter('the_content', 'add_post_content');

25. Remove Unwanted Crap from WordPress’s Head Section

WordPress add a lot of additional junk stuff in your website’s Head section like version number, WLW and RSD. Use below code to remove all crap from your website’s head section.

/************************************************************************
                    Remove Junk from Head
************************************************************************/
        remove_action('wp_head', 'rsd_link');
        remove_action('wp_head', 'wp_generator');
        remove_action('wp_head', 'feed_links', 2);
        remove_action('wp_head', 'index_rel_link');
        remove_action('wp_head', 'wlwmanifest_link');
        remove_action('wp_head', 'feed_links_extra', 3);
        remove_action('wp_head', 'start_post_rel_link', 10, 0);
        remove_action('wp_head', 'parent_post_rel_link', 10, 0);
        remove_action('wp_head', 'adjacent_posts_rel_link', 10, 0);

26. Custom Admin Login logo

If you are tired of WordPress’s branded logo on your website’s admin section, you can change it to your own logo. Just create your custom login image, name it custom-login-logo.png, and upload it to your theme’s /images/ directory. This code will take care of the rest.

/************************************************************************
                    Custom Admin Login logo
************************************************************************/
    function rukhsar_custom_admin_login_logo() {
        echo '<style type="text/css">
        h1 a { background-image: url('.get_template_directory().'/images/custom-login-logo.png) !important; }
        </style>';
    }
    add_action('login_head', 'rukhsar_custom_admin_login_logo');

27. Include Category ID in body_class & post_class

By default, WordPress body_class and post_class do not include the ID of the category of the current post. This custom function will add that for you.

/************************************************************************
        Include Category ID in body_class and post_class
************************************************************************/
    function category_id_class($classes) {
        global $post;
        foreach((get_the_category($post->ID)) as $category)
            $classes [] = 'cat-' . $category->cat_ID . '-id';
            return $classes;
    }
    add_filter('post_class', 'category_id_class');
    add_filter('body_class', 'category_id_class');

28. Hiding WordPress Admin bar on frontend

You can hide WordPress admin bar from frontend while editing your website. Simply drop the following code in your WordPress functions.php file.

/************************************************************************
        Include Category ID in body_class and post_class
************************************************************************/
    add_filter('show_admin_bar', '__return_false');

>

Wrapup

In this post we explored how we can add some basic functionalities in WordPress by using functions.php file like registering menu, removing extra stuff from our theme, enhancing WordPress admin and more.

You can find more code snippets on WordPress Codex website, which you can simply copy and paste into WordPress functions.php file. Use your WordPress functions.php file to enhance your theme and performance of the website.

Leave a Reply