Tuesday, 25 October 2022

Everything You Need to Know About the WordPress functions.php File

To get involved in WordPress development, you’ll first need to understand how the platform’s most important files work. WordPress makes it pretty easy to tinker with your site. However, it can be difficult to know where to start — or predict what your changes will actually do.

A perfect place to learn is the functions.php file, which is also known as the functions file. This is a common location for making changes and adding code to WordPress. By editing this file, you can accomplish several useful things, such as adding Google Analytics to your site, creating custom menus, or displaying a post’s estimated reading time.

What Is the functions.php File?

The WordPress functions.php file comes with all free and premium WordPress themes. To the untrained eye, it may not look like much, but the functions file is a powerful tool that enables you to do a lot of interesting things:

WordPress functions.php

The WordPress Codex describes the functions file like this:

“You can use it to call functions, both PHP and built-in WordPress, and to define your own functions. You can produce the same results by adding code to a WordPress Plugin or through the WordPress Theme functions file.”

In simple terms, the functions file enables you to add custom code to your site. It lets you create new functions or reference existing ones in customized ways. As the Codex points out, this makes the functions file very similar to a plugin, but there are some differences between the two.

The most important difference is that the functions file belongs to a specific theme. If you were to change themes or update to a newer version, the changes you’ve made would disappear.

For this reason, you should consider creating a child theme and adding the new code to the child’s functions file instead. This way, you can update the parent theme without losing your changes.

Whether you choose to use the functions file or create a plugin is entirely up to you. For now, let’s look at the different ways you can edit your functions file!

How to Edit the Functions File (2 Methods)

Editing your functions file is easy when using a standard text editor, like TextEdit or Notepad. However, before you get started, it is vitally important that you create a backup of your site and save the original, unedited functions.php file. This will enable you to restore your website if something goes wrong during the editing process.

1. Use the WordPress Editor

If you have access to the WordPress admin interface, you can edit the functions file directly from the Theme Editor. Go to Appearance > Editor:

WordPress Theme File Editor

On the right-hand side of the screen, you will see a list of all your theme files. These differ depending on which theme you use, but one of the options should be Theme Functions (functions.php).

Simply click on the file to open it in the editor:

WordPress Theme Editor functions.php file

Now, you can edit the file directly. Don’t forget to click on Update File at the bottom to save your changes when you’re done.

2. Access the File Through FTP

If you are unable to use the admin dashboard or prefer to configure files directly, you can also access the functions file using a Secure File Transfer Protocol (SFTP) client such as FileZilla.

Open your FTP tool and enter your hosting credentials to connect to your site. To find the right file, navigate to wp-content/themes/[the name of your theme]. When you open this folder, you’ll see the functions.php file:

editing the WordPress functions.php file through an FTP client

All you have to do now is to edit it using your preferred text editing software. When you’re done, save the file and overwrite it with the exact same name and extension.

8 Tricks You Can Accomplish With the WordPress Functions File

You should now be ready to start editing your functions file. To get you started, we’ll look at some changes that you can make. All you need to do is copy the provided code snippets and paste them on a new line at the very bottom of your functions file (don’t forget to save it!).

1. Add Google Analytics to Your Site

There are several ways of integrating Google Analytics with your WordPress site. One of them is by adding your credentials directly to the functions file. This method will insert the tracking code into your site’s header, ensuring that every visit is properly recorded.

Start by pasting the following code at the bottom of your functions file:

<?php

add_action('wp_head', 'wpb_add_googleanalytics');

function wpb_add_googleanalytics() { ?>

// Replace this line with your Google Analytics Tracking ID

<?php } ?>

All you have to do now is to find your Tracking ID and paste it into the line that contains the placeholder text. When you save the functions file, your site will be connected to your Google Analytics account.

Get Content Delivered Straight to Your Inbox

Subscribe to our blog and receive great content just like this delivered straight to your inbox.

2. Change the Default Login Error Message

By default, when somebody makes an unsuccessful login attempt to a WordPress site, they’ll see an error message like this:

WordPress default login error message

Unfortunately, this message is giving potential intruders information about why the attempt didn’t work. A more secure solution is to change this to a generic message instead.

You can do this easily by adding the following code to your functions file:

function no_wordpress_errors(){
return 'Something went wrong!';
}
add_filter( 'login_errors', 'no_wordpress_errors' );

See that Something went wrong! message on the second line? That message will now appear the next time an incorrect login attempt occurs:

WordPress custom login error message

You can change the text to whatever you want, as long as you keep the single quote characters. Try it out with different messages to see how it works.

3. Add the Estimated Reading Time for a Post

This neat trick enables you to calculate and display the estimated amount of time required to read a post. Your visitors can then get a general idea of the content’s length right away.

To implement this code, you will need to make two separate edits. The first one happens within the functions.php file, where you’ll want to paste the following snippet:

function reading_time() {
$content = get_post_field( 'post_content', $post->ID );
$word_count = str_word_count( strip_tags( $content ) );
$readingtime = ceil($word_count / 200);
if ($readingtime == 1) {
$timer = " minute";
} else {
$timer = " minutes";
}
$totalreadingtime = $readingtime . $timer;
return $totalreadingtime;
}

However, this snippet only performs the calculation. You’ll now need to add the following code wherever you want the results to be displayed:

echo reading_time();

For example, you could add it to the metadata that appears alongside each post. Every theme is constructed differently, but typically you’ll find it in template-parts > post > content.php:

WordPress functions.php estimated reading time

The estimated reading time will now appear in each post’s header alongside the date.

4. Remove the WordPress Version Number

Old versions of WordPress may contain security flaws that malicious hackers and bots can exploit. One way to avoid this risk is to hide which version of WordPress your site uses. This is called security through obscurity.

Before we move on, it’s important to note that obscurity should never be your only security measure. It’s more like adding an extra bulwark to your already secure WordPress fortress.

Hiding your version number only requires adding the following code snippet to the functions file:

remove_action('wp_head', 'wp_generator');

The version number will now be removed from all areas of your site, including its code and your RSS feed.

5. Automatically Update Your Copyright Notice

Updating the year in your copyright notice is one of those little tasks that’s easy to forget. Fortunately, you can edit your functions file to automatically generate the copyright date based on the year when your first post was written.

Paste the following code into your functions file:

function wpb_copyright() {
global $wpdb;
$copyright_dates = $wpdb->get_results("
SELECT
YEAR(min(post_date_gmt)) AS firstdate,
YEAR(max(post_date_gmt)) AS lastdate
FROM
$wpdb->posts
WHERE
post_status = 'publish'
");
$output = '';
if($copyright_dates) {
$copyright = "© " . $copyright_dates[0]->firstdate;
if($copyright_dates[0]->firstdate != $copyright_dates[0]->lastdate) {
$copyright .= '-' . $copyright_dates[0]->lastdate;
}
$output = $copyright;
}
return $output;
}

Then add the following code wherever you want the copyright information to be displayed:

<?php echo wpb_copyright(); ?>

You’ll now see the dynamically updating copyright date on your site.

A dynamically-updating copyright date on a website

In our case, we added the date to the footer.php file, so it would be displayed at the bottom of the page.

6. Add Custom Menus

Most themes have pre-defined navigation menus. However, what if you want to create your own menu and place it wherever you want on your site?

All you need to do is paste this code into your functions file:

function wpb_custom_new_menu() {
register_nav_menu('my-custom-menu',__( 'My Customized Menu' ));
}
add_action( 'init', 'wpb_custom_new_menu' );

You can replace ‘My Customized Menu’ with the name you want to give the menu. If you go to Appearance > Menus in your admin area, you should see the new option listed on the page:

customize your WordPress menus using the functions.php file

You can now add the new menu anywhere on your site.

<?php
wp_nav_menu( array(
'theme_location' => 'my-custom-menu',
'container_class' => 'custom-menu-class' ) );
?>

Most probably, you’ll want to place this code in the header.php file. This will place the menu at the very top of your site.

7. Customize Your Excerpts

Excerpts are short sample descriptions of your posts that you can display on your homepage or blog feed. By default, all excerpts have the same length and link text, but you can change that.

First, let’s alter the text of the link that takes you from the excerpt to the full post. This is usually “Read more” or “Continue reading,” but you can make it whatever you want by pasting the following snippet into your functions file:

function new_excerpt_more($more) {
global $post;
return '<a class="moretag" href="'. get_permalink($post->ID) . '"> Read the full article...</a>';
}
add_filter('excerpt_more', 'new_excerpt_more');

Here, the link text has been set to Read the full article…

customize WordPress excerpts by editing the functions.php file

Then, let’s change the length of the excerpt. Paste this code into your functions file:

function new_excerpt_length($length) {
return 20;
}
add_filter('excerpt_length', 'new_excerpt_length');

By default, the standard length is 55 words. However, in this example, it’s been set to 20. You can change the number to whatever you wish.

8. Generate a Random Background to Your Site

Finally, let’s end with a fun design trick. This tweak lets you randomly generate a new background color for your site every time somebody visits it. Start by adding the following code to the functions file:

function wpb_bg() {
$rand = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f');
$color ='#'.$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].
$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)];
echo $color;
}

This code generates the HTML tag for the colors, so all you need to do now is to make sure it gets applied to the page. To do that, you’ll need to find the <body> tag, which should look like this:

<body <?php body_class(); ?>>

This is usually in the header.php file but can be elsewhere, depending on your theme. When you’ve located the right line, simply replace it with the following code:

<body <?php body_class(); ?> style="background-color:<?php wpb_bg();?>">>

Save your file and open your website. You should see that it has a new background color:

create random background colors on reload by editing your WordPress functions.php file

Reload the page, and you’ll see a new color every time:

create random background colors on reload by editing your WordPress functions.php file

This is obviously not the right design choice for every site, but it’s a neat trick for some!

Edit Your functions.php File

The WordPress functions.php file is the perfect place to tinker with your site’s default functionality. It’s a powerful file that gives you a lot of control over your site once you understand how it works.

Depending on your WordPress theme, you might be able to use the built-in Theme File Editor to access and edit your functions.php file. Otherwise, you can access it via FTP. Then, you can use custom code to do everything from displaying the estimated reading time of a post to customizing your excerpts.

Do More with DreamPress

DreamPress Plus and Pro users get access to Jetpack Professional (and 200+ premium themes) at no added cost!

Managed WordPress Hosting - DreamPress

The post Everything You Need to Know About the WordPress functions.php File appeared first on Website Guides, Tips & Knowledge.



source https://www.dreamhost.com/blog/guide-to-wp-functions/

No comments:

Post a Comment

Creating and Mastering GA4 Explorations

In the switch from Universal Analytics (UA) to Google Analytics 4 (GA4) — which will go fully into effect July 2023 — a lot of things have...