GuidesHow To

15+ Useful And Basic Tricks For WordPress Function Files 2024 

Hey, do you want to optimize the website performance and secure your website, and also try to give your audience the best user experience? Do you want to know useful tricks for the WordPress function files that not only protect your website against vulnerabilities but also improve your website functionalities and user engagement?  

Then I got you, and you landed at the perfectly right place!  

The WordPress functions.php file stands as a core element within every WordPress setup. It works as a magic wand that transforms your website into countless different ways. It wields substantial influence over your website’s performance and behavior.   

But for newbies who have no technical background, understanding the main purpose and what are the potential risks associated with it, like what is the purpose of the WordPress function file and how to use it without affecting your site performance.   

So, let’s cut to the chase and learn some useful tricks for WordPress function files.  

What Are WordPress Function Files, And How Does It Work? 

The functions.php file is an integral part of almost every WordPress setup, typically residing in your theme directory, including child themes. 

But you might wonder, what’s its purpose, and why should we use it? 

It works the same as a WordPress plugin, as it enhances the WordPress functionalities.  

However, there’s a crucial difference. But the tricks that we use for function.php files are applicable as long as you stick with the theme because WordPress function files are theme dependent while plugins are independent of the theme and work as long as you install it in your WordPress site.  

This versatile file accommodates both PHP code and native WordPress functions. If you’re familiar with theme hooks, you can even craft your custom hooks using functions.php. 

As you know, it is the popular quote “Great power comes with great responsibility.” The functions file is potent, but it requires careful handling. So, let’s delve into when and when not to employ functions.php wisely. 

Consider These Steps Before Applying The Tricks On Function.PHP 

Because when you work with a function PHP file, it involves adding code to the website. So even a single comma mistake in the code creates an error on your site like a WordPress white screen of death.   

Although the latest WordPress version can easily handle these errors, you still need to avoid these potential issues from happening.   

So, it is best to follow the underlying practices before applying underlying tricks.  

Before applying these functions.php code snippets to your WordPress site, it is recommended to apply these tricks on the starting version of your website. This will help you to check and analyze if you encounter any potential errors.  

Step 1: Test Your Code on a Staging Site 

A staging site is the exact copy of your live website, and it works as a safe site for your website, you can easily test the changes in your function php file without affecting your real site.  

Using the staging site as a tester will help you identify and fix any issue if you encounter any problem in your coding before your final result reaches your live website.   

Step 2: Back Up Your Live Website 

Creating a backup for your website is necessary before starting changes to your live website. Because backup works as a safety measure, even if something goes wrong with your coding in your function file, then you can easily restore your website to its original state.  

Step 3: Use a Child Theme 

It is essential to use the child theme instead of the parent theme when you make changes to the function.PhP file. It ensures that your customization won’t be overwritten when you update your theme.  

You can update the parent theme without losing your custom code by using a child theme.  

Top 15+ Tricks For WordPress Functions Files:

1. Add Google Analytics to Your Site:

Adding Google Analytics to your WordPress site is an essential step. If you are serious about your website business or running an online store, then it grants you valuable insights into your audience’s behavior, empowering you to enhance your site functionality and performance. 

Typically, Google Analytics is integrated using a plugin. However, there’s an alternative way of installing Google Analytics which is manual implementation through the WordPress functions.php file. Here’s what it entails: 

You can find the code snippet here: [insert a link to code snippet] 

To activate this snippet, all you need to do is replace the content between “<script async…” and the closing “</script>” with your unique Google Analytics tracking code. 

In short, if you add Google Analytics by using this approach, then you will get a clear understanding of your audience’s behavior and interactions. Moreover, if you do not want your website overloaded with different plugins, then it is the perfect option to consider.

2. Do not Expose Specific WordPress Login Errors:

When someone puts incorrect credentials like a username or password, then WordPress provides a particular error message and tells it in the notification that the username or password is incorrect which makes it easier for the hackers to infiltrate the website.  

To increase your website security, it is necessary to employ the following code snippet to modify the error message and make it less revealing:  

function custom_login_error_message() { return “Your login credentials are incorrect. Please try again.”;} 

add_filter(‘login_errors’, ‘custom_login_error_message’); 

To make this work, simply replace the text within the double quotation marks (” “) with your preferred error notification (you can use some code words that can only be understood by you). This change ensures that any wrong login attempts receive a generic message, making it harder for malicious individuals to pinpoint the exact login issue. 

3. Show The Word Count In An Article:

The length of the blog post is easily estimated with the help of the word count. In this way, your audience can decide whether they want to spend their time reading your content or not.  

Now I will tell you how to add code in your php file to add word count in your blog post.   

Step 1. Modify the functions.php File 

  • First, open your WordPress theme’s functions.php file. Access this file via the WordPress dashboard > Appearance > Theme Editor 
  • Now, open the function.php file and paste the underlying code at the end of the function file 

function count_words_in_content($content) {$word_count str_word_count(strip_tags($content)); return $word_count;}}  

Now, this code will calculate the word count and remove the HTML tags from your blog posts.  

Step 2. Display the Word Count in Your Posts 

Next, you need to select the area where you want to display the word count within your posts.  

To do this, use the following code and place it where you’d like the word count to appear in the post: 

<?php 

$word_count = count_words_in_content(get_the_content()); 

echo ‘<div class=”word-count”>This article contains ‘ . $word_count . ‘ words.</div>’; 

?> 

?  

The most interesting part is that you can easily customize the message and style by using CSS ( if you have coding knowledge) like in this code “this article contains” is the main message that works on the word count in the post. 

Step 3: Locate Your Post Template File 

All WordPress themes come with different structures so find the appropriate file and insert the code that I have mentioned in the previous step. If you are finding it difficult to identify the correct template, then you can use the “What the File” plugin. This plugin will help you in which file is responsible for displaying the page or post you’re currently on. 

Step 4: Insert the Code into Your Post Template: 

After opening the template file, find the section where you want to show your word count to the audience. Insert the code snippet in the particular location where you want to display your word count.  

Save the changes. Now, WordPress will display your word count to the readers in every post.   

4. Add Estimated Reading Time In Blog Posts  

If you do not want to display the word count, then you can also show the reading time. 

In your WordPress theme’s functions.php file, insert the following code: 

function reading_time() 

{ 

    ob_start(); 

    the_content(); 

    $content = ob_get_clean(); 

    $word_count = size of(explode(” “, $content)); 

    $reading_speed = 200; // Adjust this number based on your readers’ pace 

    $minutes = ceil($word_count / $reading_speed); 

    if ($minutes == 1)  

{ 

         return “1 minute read”;   

 

    Else 

  { 

         return $minutes . ” minutes read”; 

 

} 

This code calculates the estimated reading time based on a default reading speed of 200 words per minute. You can modify this value to match your audience’s reading pace. 

Display Reading Time in Your Posts: 

This step is also similar to the previous step. Wherever you want to display the reading time within your posts, add the following line of code:  

echo ‘<div class=”reading-time”>’ . reading_time() . ‘</div>’;  

If you want to adjust it, then adjust the HTML and text to align with your site’s style. The actual reading time will appear where it says reading_time(), and the echo command ensures it’s displayed.  

If you are not certain about your reader’s reading speed and your readers may have a different reading pace, modify the $reading_speed variable in the code to suit their preferences. 

5. RSS Feed

If you do not want your post to appear in your RSS feed immediately right after you hit the Publish Button, then use this trick.  

It is a good trick because it helps you to catch those typos or mistakes that often escape during proofreading. But the problem is that if your post is in the RSS feed, then your mistake is thoroughly exposed to the audience.  

But, there’s a simple way to prevent this. For this, follow these steps: 

Step no 1. Access Your Theme’s functions.php File: 

Go to your WordPress theme’s functions.php file.  

Step no 2. Insert the Delay Code: 

Add the following code snippet to your functions.php file: 

function delay_rss_feed($where) { 

    global $wpdb; 

    if (is_feed()) { 

        $where .= ” AND post_date > ‘” . date(‘Y-m-d H:i:s’, strtotime(‘-10 minutes’)) . “‘”; 

    } 

    return $where; 

} 

add_filter(‘posts_where’, ‘delay_rss_feed’); 

This code introduces a delay of 10 minutes (you can adjust this value) before your posts appear in your RSS feed.  

Step no 3. Customize the Delay Timing: 

You can change the number according to your preference to delay the duration before your post appears in the RSS feed.  

When you use this trick in your function.php file, your blog posts won’t immediately show up in your RSS feed when you publish them. This gives you enough time to catch and correct any errors before they become visible to your readers.

6. Detect When The Visitor Is On A Smartphone

If you want your websites to also work best on mobile devices, then use the simple code snippet in your WordPress functions.php file that will check how many people are visiting your website via mobile devices.  

People mostly use mobile devices for browsing different websites, so It is necessary to make your website look and perform well on mobile devices to increase your website traffic and engagement.  

For this, add a code snippet in your WordPress function.php file. This code is really helpful for you in checking whether the audience is using the mobile device, or they are browsing through other devices like MacBook or PC.  

  • Access Your Theme’s functions.php file 
  • Go to your WordPress theme’s functions.php file, and add the following code to your functions.php file: 

if (wp_is_mobile()) { 

    // This part of the code will run if the visitor is on a mobile device. 

    // You can use this section to make your website look better on mobile screens. 

} 

This code checks if the user is landing on your site from a mobile device. If they are, you can customize the appearance of your site for mobile users in the section where it says “// This part of the code will run if the visitor is on a mobile device.”  

On another note, you can also use the plugin. If you add the code, it doesn’t mean that you cannot use the plugin. You can add a plugin for additional functionalities. This code will just help you in making your website load faster on mobile devices. 

7. Remove The Continue Reading From Your Blog Posts:

Most WordPress templates come with Continue Reading features, in which readers need to click to read further content. The purpose of this feature is to lessen the crowd on a page. If you don’t want this to appear on your blog posts then remove it by using the function. Php file.   

For this, add the underlying code in your WordPress theme and replace the default name of the theme (twenty-eleven) with your WordPress theme file name. 

function twentyeleven_continue_reading_link() { 

    return ‘ <a href=”‘. esc_url( get_permalink() ) . ‘”>’. __( ‘[…]’, ‘twenty eleven’ ) . ‘</a>’; 

} 

endif; 

function twentyeleven_auto_excerpt_more( $more ) { 

    return ” . twentyeleven_continue_reading_link(); 

} 

add_filter( ‘excerpt_more’, ‘twentyeleven_auto_excerpt_more’ );

8. Remove Scripts From Header To Footer

When you install a WordPress theme, it occasionally comes with certain styles and scripts that are not useful for your website.   

And you need to remove these scripts and compliments to improve the website’s speed and performance.   

For this, you need to remove the scripts from the header to the footer through WordPress functions.  

Just add these source code to the page template. 

  • Go to the WordPress dashboard > Appearance > Theme Editor  
  • Then go to the function.php file and click on it to edit. 
  • In the Theme Editor, on the right side, you’ll see a list of theme files. Look for the “functions.php” file,  

Insert the following code into the “functions.php” file: 

/** 

 * Dequeue the Parent Theme scripts. 

 */ 

function remove_unnecessary_scripts() { 

    wp_dequeue_script( ‘comment-reply’ ); // If you’re using disqus, etc. 

    wp_dequeue_script( ‘jquery_ui’ ); // jQuery UI, no thanks! 

    wp_dequeue_script( ‘fancybox’ ); // Nah, I use FooBox 

    wp_dequeue_script( ‘wait_for_images’ ); 

    wp_dequeue_script( ‘jquery_easing’ ); 

    wp_dequeue_script( ‘swipe’ ); 

    wp_dequeue_script( ‘waypoints’ ); 

} 

add_action( ‘wp_print_scripts’, ‘remove_unnecessary_scripts’, 100 ); 

/** 

 * Dequeue the Parent Theme styles. 

 */ 

function remove_unnecessary_styles() { 

    wp_dequeue_style(‘additional-parent-style’); 

    wp_deregister_style(‘additional-parent-style’); 

} 

add_action(‘wp_enqueue_scripts’, ‘remove_unnecessary_styles’, 100); 

Now click the “Update File” button and save your changes. 

9. Update The Copyright Notification Automatically:

As you know, updating the copyright date on the latest date is an important, but easily forgettable task, so you need to update this automatically. For this, you need to edit your function file and add the code into the function so this notice is generated automatically.  

For this, you need to paste the underlying code into your function file: 

function wpb_copyright() { 

global $wpdb; 

$copyright_dates = $wpdb->get_results(“ 

SELECT 

YEAR(min(post_date_gmt)) AS first date, 

YEAR(max(post_date_gmt)) AS last date 

FROM 

$wpdb->posts 

WHERE 

post_status = ‘publish’ 

“); 

$output = ”; 

if($copyright_dates) { 

$copyright = “© ” . $copyright_dates[0]->firstdate; 

if($copyright_dates[0]->first date != $copyright_dates[0]->last date) { 

$copyright .= ‘-‘ . $copyright_dates[0]->last date; 

} 

$output = $copyright; 

} 

return $output; 

} 

For displaying the copyright date and other relevant information on all pages of the website, add the underlying code.

<?php echo wpb_copyright(); ?> 

Mostly, the copyright information is added at the footer.php file then you see the copyright information at the bottom of the page. 

10. Add Customized Menu 

Although many themes come with default navigation menus, if you are not satisfied with the predefined navigation menu, then you can create your own and add those menus according to your preferences.  

function wpb_custom_new_menu() { 

register_nav_menu(‘my-custom-menu’,__( ‘Our Customized Menu’ )); 

} 

add_action( ‘init’, ‘wpb_custom_new_menu’ ); 

In this code, you can replace our customized menu with the suitable one you want to give the menu.  

  • Go to the WordPress dashboard via your admin account  
  • Then Go to Appearance > Menu  
  •  Here, you will see the Our Customized Menu option. 

11. Enable The Threaded Comments 

WordPress contains a feature that allows the audience to view the comment easily. To enable the threaded comments on WordPress, you need to enable the comments in your administrative area.  

Visit your WordPress admin account and then Setting > Discussion Area. You also need to add the javascript in your header to make commenting more easier.    

Now, add the underlying code in your Function file. 

// enable threaded comments 

function enable_threaded_comments(){ 

  if (!is_admin()) { 

  if (is_singular() AND comments_open() AND (get_option(‘thread_comments’) == 1)) 

    wp_enqueue_script(‘comment-reply’); 

  } 

} 

add_action(‘get_header’, ‘enable_threaded_comments’); 

12. Disable the Search Feature in WordPress 

Sometimes, the need for the search bar is not essential, and you need to remove this search bar from the design. Even if you remove the search bar the functionality of the search bar will remain present.   

So, add the underlying code into the function file, disable the search feature, and remove the search bar from your design in WordPress. 

  • Go to Dashboard > Appearance > Theme Editor > functions.php  
  • Now insert the underlying code into the function.php file  

function disable_search_function($query, $error = true) { 

    if (is_search()) { 

        $query->is_search = false; 

        $query->query_vars[‘s’] = false; 

        $query->query[‘s’] = false; 

        // Redirect to 404 page 

        if ($error == true) 

            $query->is_404 = true; 

    } 

} 

add_action(‘parse_query’, ‘disable_search_function’); 

add_filter(‘get_search_form’, function($a) { 

    return null; 

}); 

After adding the code, click the “Update File” button to save your changes. 

13. Enable the Google Adsense Short Code 

Adding Google AdSense is an important and popular ad element that is mostly used by bloggers. If you want to add ads anywhere on the WordPress site, then you need to add this. If you do not want to be limited to the specific theme-designated spots; you can create a shortcode for Google AdSense using the following simple code. 

  • Go to Dashboard > Appearance > Theme Editor > functions.php  
  • And add the underlying code in your funation.php file  

function insert_adsense() { 

    return ‘<div id=”adsense”> 

        <script type=”text/javascript”> 

            <!– 

            google_ad_client = “pub-XXXXXXXXXXXXXX”; 

            google_ad_slot = “4668915978”; 

            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’, ‘insert_adsense’);  

Now click the “Update File” button and save the changes.  

If you want to add the Google Adsense ad anywhere on the website, then simply use the [adsense] shortcode in the WordPress editor when creating or editing a post or page. This shortcode will automatically display the Google AdSense ad unit wherever it’s placed within the content. 

14. Add the Customized Dashboard Logo:

When you add the code in the function file, the logo will appear in the top left corner of your dashboard, making it visually appealing and giving your dashboard a customized and professional look. 

If you want to personalize your WordPress dashboard by adding a custom logo, you can achieve this simple code snippet.   

Insert the following code snippet into the “functions.php” file: 

// Hook to display the custom logo in the dashboard header 

function my_custom_logo() { 

    echo ‘<style> 

        #wp admin bar #wp-admin-bar-wp-logo > .ab-item .ab-icon:before { 

            background-image: url(‘ . get_template_directory_uri() . ‘/images/custom-dashboard-logo.png); 

            background-size: cover; 

            content: none; 

            width: 20px; 

            height: 20px; 

        } 

    </style>’; 

} 

add_action(‘admin_head’, ‘my_custom_logo’); 

 15. Add an Icon (Favicon)

A favicon is an icon that is associated with a particular website that makes your website stand out. Typically, it is displayed right next to the website name in the browser tabs.   

If you also want to add the icon to your website, then First, choose the icon of your website, then add the favicon code to the header.php or add the underlying code by following the underlying steps;   

Go to Dashboard > Appearance > Theme Editor > functions.php  

Now, add the underlying code in your funation.php file:  

// Add your own favicon to the blog 

function add_favicon_to_blog() { 

    echo ‘<link rel=”icon” href=”‘ . site_url(‘/favicon.ico’) . ‘” type=”image/x-icon” />’; 

} 

add_action(‘wp_head’, ‘add_favicon_to_blog’); 

Final Words: 

I provided limited tricks that are basic, but the sky’s the limit, you can also come up with new ideas to make your website more functional and better. 

If you have limited technical knowledge, then you can also use the plugin, but customizing via the function php file makes your website more personalized.  

In the WordPress function.php file, you can add custom code to make your website attractive and more functional.  

You might have heard the rumor of it, “Be cautious while handling this main core of WordPress.” So, it is necessary that you have some technical background to handle this.  

So, it is a wise strategy to use the child theme to protect your changes when you update your site’s design because, in this way, your changes won’t get overwritten when you update the changes in your website. Make a backup for your site before adding code and consider testing it on the staging site.  

So, consider the above-mentioned steps before starting to add tricks to your function file.  

I hope this article will be helpful for you and you can make your website better.   

Frequently Asked Questions (FAQs): 

What Is The Function File In WordPress? 

The function.php file works like the main system or brain of your WordPress website. If you want to make your website’s appearance attractive and add features to increase your website functionality, then the function.php file is the place where you need to add the codes. When you add the code to your file, your website will look more customized and unique, providing the best experience to your audience.  

How To Use The Functions In WordPress? 

If you have no technical background or little coding knowledge, then you have two ways to add functions to your WordPress suite,  

  • By using plugins  
  • By getting assistance from a web developer  

You can either get the assistance of a web developer or use the plugin to create a customized website that meets your website’s needs.   

What Is The Use Of The Function File? 

Function files in WordPress act like messengers that can both receive and send information. These files take data through input parameters and send data via output parameters. While script files do not have such property. The information needs to be written within the function php files.   

Where Is The Function File In WordPress? 

The functions. The PHP file for WordPress core is located in your wp-includes folder. Your theme’s functions. The PHP file is located in wp-contentthemesyour theme. 

There are two places where you can find the function php file. The function.php file for the core of WordPress is stored in the wp-includes folder.  

If you are using a specific theme, then the functions.php file for your specific theme is located in the wp-content directory, under themes, and within the folder of the theme you’re using.  

In short, you can find the WordPress theme function. php file in  

  • the core of the WordPress theme  
  • In the wp-content → themes → your theme

Related Articles

Leave a Reply

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

Back to top button