👋🏼Welcome to my WP-Host blog where I am excited to share my knowledge and expertise on WordPress hosting and website construction tutorials with you. Let’s connect and learn from each other! You can reach me at info@yrshare.com.

(如果你会中文,可以点击微信图标与我联系。)

扫一扫加我

注:因个人英文水平有限,所以暂时只能为懂中文的朋友提供wordpress建站服务

微信:18200592859 或 yrwordpress

WordPress function file Functions.php tutorial guide (super detailed)

WordPress function file Functions.php tutorial guide (super detailed)-WP-Host

WordPress function file Functions.php tutorial guide (super detailed): This article is a guide about Word Press functions, the main content includes:

  1. Introduces the concepts and functions of Word Press functions, and how to use functions to expand and customize Word Press websites.
  2. The commonly used Word Press functions are explained in detail, including Word Press core functions, theme functions, plug-in functions, etc.
  3. Classified and summarized Word Press functions, such as database functions, user functions, mail functions, query functions, etc., which are convenient for developers to find and use.
  4. It focuses on some commonly used Word Press functions, such as wp_head(), wp_footer(), wp_enqueue_script(), wp_enqueue_style(), etc., and how to use them to add styles and scripts.

All in all, this article provides a systematic guide to Word Press functions, which is of certain reference value for developers who are learning or using Word Press.

【WP-Host/悦然wordpress建站】

Many effects of the wordpress website can be achieved by modifying the functions.php file. For example, many code snippets shared by WP-Host are added to functions.php. So we will talk about the functions.php file in detail in the wordpress tutorial we will share next.

What is the functions.php file?

WordPress function file Functions.php tutorial guide (super detailed)-WP-Host

The functions.php file for Word Press is included with all free and paid Word Press themes.
To the untrained eye, it may not seem like much, but function files are a powerful tool that allow you to do a lot of interesting things.

The feature file is described in the WordPress Codex like this:

You can use it to call functions, including PHP and the built-in Word Press, and define your own functions. You can produce the same result by adding code to a Word Press plugin or through a Word Press theme functions file.

In simple terms, function files enable you to add custom code to your site. It allows you to create new functions or reference existing functions in a custom way. As Codex points out, this makes function files very similar to plugins, with some differences.

The most important difference is that function files belong to a specific theme. If you change the theme or update to a newer version, your changes will disappear. For this reason, you should consider creating a child theme and adding the new code to the child theme’s functions file. This way, you can update the parent theme without losing your changes.

Whether you choose to use a function file or create a plugin is entirely up to you, depending on your needs. Now let’s look at the different ways of editing function files.

How to edit function files

Editing function files is as easy as using a standard text editor such as(Text Edit or Notepad). Before starting, it’s important to create a backup of your site and save the original, unedited functions.php file.
This will allow you to restore your site if something goes wrong during editing.

1. Use the Word Press editor

If you have access to the Word Press admin interface, you can edit the features file directly from the theme editor. Go to [Appearance > Editor].

WordPress function file Functions.php tutorial guide (super detailed)-WP-Host

On the right side of the screen, you can see a list of all files included in the theme. These vary depending on the theme you use, but one of the most important options should be Theme Functions (functions.php).
Just click on the file to open it in the editor.

WordPress function file Functions.php tutorial guide (super detailed)-WP-Host

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

2.Access files via FTP

If you don’t have access to the admin dashboard or prefer to configure files directly, you can also use FTP tools like FileZilla to access feature files.

Open your FTP tool and enter the server account information to connect to your site. To find the correct file, navigate to wp-content/themes/[the name of your theme]. When you open this folder, you will see the functions.php file.

WordPress function file Functions.php tutorial guide (super detailed)-WP-Host

All you have to do now is edit it with your favorite text editing software. After making changes, save and overwrite the function file with the exact same name and extension.

Some small cases of using Word Press function files

You should now be able to start editing your functions file. To get you started, here are some examples of the various tweaks 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 the function file (don’t forget to save it!).

1.Add Google Analytics to your website

There are various ways to integrate Google Analytics with your Word Press website. One of them is to add your credentials directly to the function file. This inserts analytics tracking into the header of your site, ensuring each visit is properly captured.

Start by pasting the following code at the bottom of the function 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 need to do now is find your tracking ID and paste it into the line containing the placeholder text. When you save the function file, your site will be connected to your Google Analytics account.

2. Change the default login error message

By default, when someone tries to log into a WordPress website and fails, they see an error message like this:

WordPress function file Functions.php tutorial guide (super detailed)-WP-Host

This is not ideal because the site is giving potential intruders information about why the attempt failed.
A safer solution is to change it to a generic message.

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

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

See the “Something went wrong!” message on the second line?
This is the message that will appear the next time an incorrect login attempt occurs:

WordPress function file Functions.php tutorial guide (super detailed)-WP-Host

You can change it to whatever you want as long as you keep the single quote character. Try using a different message and see how it works.

3.Add an estimated reading time for the article

This neat trick enables you to calculate and display the estimated time it will take to read a post. Your visitors can then get an immediate overview of how long the content will be.

To implement this code, you need to make two separate edits. The first is done as usual to the function file, where you need to paste the following code 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 only performs calculations. You now need to add the following code wherever you want to display the results:

echo reading_time();

For example, you can add this to the metadata displayed next to each article.
Every theme is structured differently, but in the 2017 theme it’s located in template-parts > post > content.php.

WordPress function file Functions.php tutorial guide (super detailed)-WP-Host

Estimated reading time will now appear in the title of each article, along with the date.

4.Remove the Word Press version number

Older versions of Word Press may contain security flaws that malicious hackers and bots can exploit.
One way to avoid this risk is to hide which version of Word Press your website uses. This is known as security through obscurity.

Before we continue, it’s important to note that obscurity should not be your only security measure.
It’s more like adding an extra bastion to your already secure WordPress bastion.

Hiding your version number simply requires you to add the following very simple code snippet to your function file:

remove_action('wp_head', 'wp_generator');

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

5.Automatically update your copyright notice

Updating the year in a copyright statement is one of those little tasks that is easy to forget. One way you can keep up is to use this trick, which automatically generates a copyright date based on the year your first article was published.

Paste the following code into your function 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 to display the copyright information:

<?php echo wpb_copyright(); ?>

You will now see a dynamically updated copyright date on your website.

WordPress function file Functions.php tutorial guide (super detailed)-WP-Host

In this example, we are adding the date to the footer.php file so that it will be displayed at the bottom of the page.

6.Add custom menu

Most themes come with predefined navigation menus, but what if you want to create your own and place it anywhere on your website? All you need to do is paste this code into your function 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 Custom Menu” with whatever you want to name your menu. If you go to Appearance > Menus in the admin area, you should see the new option listed.

WordPress function file Functions.php tutorial guide (super detailed)-WP-Host

You can now add new menus anywhere on your site.

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

Most commonly, you will need to place this code in your header.php file.

7.Customize your summary

A summary is a short sample description of your article that can appear on your homepage or in search results instead of the full article content. By default, all excerpts have the same length and link text, but you can change this.

First, let’s change the text of the link that takes you from the summary to the full article. This is usually “read more” or “keep reading”, but you can make whatever you want by pasting the following snippet into your function 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…:

WordPress function file Functions.php tutorial guide (super detailed)-WP-Host

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

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

By default, the standard length is 55 words. In this example, it is set to 20. You can change the numbers to whatever you want.

8.Add a random background to your website

Finally, let’s end with an interesting design trick. This tweak allows you to randomly generate a new background color for your website every time someone visits it. First add the following code to your function 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 HTML markup for the color, so all you need to do now is make sure it’s applied to the page. For this, you need to find the <body> tag, which should look like this:

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

This is usually located in the header.php file, but can be elsewhere, depending on your theme.
Once you find the correct line, just replace it with the following code:

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

Save your file and open your website now. You should see it have a new background color.

WordPress function file Functions.php tutorial guide (super detailed)-WP-Host

Reload the page and you’ll see a new color each time.

WordPress function file Functions.php tutorial guide (super detailed)-WP-Host

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

Summary

The functions.php file of your Word Press website theme is the perfect place to start learning how to modify your site’s default functions. This is a powerful file, and once you understand how it works, you have a lot of control over it.

wordpress网站的很多效果都可以通过修改functions.php文件来实现,比如WP-Host分享的很多代码片断都是添加到functions.php中的。所以接下来分享的wordpress教程我们就详细来讲讲functions.php文件。

什么是functions.php文件?

WordPress function file Functions.php tutorial guide (super detailed)-WP-Host

WordPress的functions.php文件包含在所有免费和付费WordPress主题中。对于未受过训练的人来说,它可能看起来不多,但函数文件是一个强大的工具,可以让您做很多有趣的事情。

WordPress Codex这样描述的功能文件:

您可以使用它来调用函数,包括PHP和内置WordPress,并定义您自己的函数。您可以通过向WordPress插件或通过WordPress主题功能文件添加代码来产生相同的结果。

简单来说,函数文件使您能够向站点添加自定义代码。它允许您以自定义方式创建新函数或引用现有函数。正如Codex指出的那样,这使得函数文件非常类似于插件,但两者之间存在一些差异。

最重要的区别是函数文件属于特定主题。如果您要更改主题或更新到更新版本,您所做的更改将会消失。出于这个原因,您应该考虑创建一个子主题并将新代码添加到子主题的函数文件中。这样,您可以在不丢失更改的情况下更新父主题。

是选择使用函数文件还是创建插件完全取决于您,具体取决于您的需要。现在让我们看看编辑函数文件的不同方式。

如何编辑函数文件

编辑函数文件就像使用标准文本编辑器(如 TextEdit 或记事本)一样简单。在开始之前,创建站点的备份并保存原始的、未经编辑的functions.php文件非常重要。这将使您能够在编辑过程中出现问题时恢复您的站点。

1. 使用WordPress编辑器

如果您有权访问 WordPress 管理界面,则可以直接从主题编辑器编辑功能文件。转到外观 > 主题编辑器

WordPress function file Functions.php tutorial guide (super detailed)-WP-Host

在屏幕的右侧,您可以看到主题中包含的所有文件的列表。这些因您使用的主题而异,但最重要的选项之一应该是Theme Functions (functions.php)。只需单击该文件即可在编辑器中打开它。

WordPress function file Functions.php tutorial guide (super detailed)-WP-Host

现在,您可以直接编辑文件。完成后,不要忘记单击底部的更新文件以保存更改。

2.通过FTP访问文件

如果您无法使用管理仪表板或更喜欢直接配置文件,您还可以使用FileZilla等FTP工具访问功能文件。

打开您的FTP工具并输入服务器账号信息以连接到您的站点。要找到正确的文件,请导航到wp-content/themes/[the name of your theme]。当您打开此文件夹时,您将看到functions.php文件。

WordPress function file Functions.php tutorial guide (super detailed)-WP-Host

您现在要做的就是使用您喜欢的文本编辑软件对其进行编辑。完成更改后,使用完全相同的名称和扩展名保存并覆盖函数文件。

使用WordPress函数文件的一些小Case

您现在应该可以开始编辑您的函数文件了。为了让您开始,以下是您可以进行的各种调整的一些示例。您需要做的就是复制提供的代码片段并将它们粘贴到函数文件最底部的新行上(不要忘记保存它!)。

1. 将Google Analytics添加到您的网站

有多种方法可以将Google Analytics与您的WordPress网站集成。其中之一是将您的凭据直接添加到函数文件中。这会将分析跟踪插入您网站的标题中,确保正确捕获每次访问。

首先将以下代码粘贴到函数文件的底部:

<?php

add_action('wp_head', 'wpb_add_googleanalytics');

function wpb_add_googleanalytics() { ?>

// Replace this line with your Google Analytics Tracking ID

<?php } ?>

您现在要做的就是找到您的跟踪ID并将其粘贴到包含占位符文本的行中。当您保存函数文件时,您的站点将连接到您的Google Analytics帐户。

2. 更改默认登录错误信息

默认情况下,当有人尝试登录WordPress网站失败时,他们会看到如下错误消息:

WordPress function file Functions.php tutorial guide (super detailed)-WP-Host

这并不理想,因为该站点正在向潜在入侵者提供有关尝试失败的原因的信息。更安全的解决方案是将其更改为通用消息。

您可以通过将以下代码添加到您的函数文件中轻松完成此操作:

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

看到“Something went wrong!” 第二行的消息?这是下次发生错误登录尝试时将出现的消息:

WordPress function file Functions.php tutorial guide (super detailed)-WP-Host

只要保留单引号字符,您就可以将其更改为您想要的任何内容。尝试使用不同的消息,看看它是如何工作的。

3. 添加文章的预计阅读时间

这个巧妙的技巧使您能够计算和显示阅读帖子所需的估计时间。然后,您的访问者可以立即大致了解内容的时长。

要实现此代码,您需要进行两次单独的编辑。第一个像往常一样对函数文件完成,您需要在其中粘贴以下代码段:

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;
}

但是,这仅执行计算。您现在需要在想要显示结果的任何位置添加以下代码:

echo reading_time();

例如,您可以将其添加到每个文章旁边显示的元数据中。每个主题的构造都不同,但在二〇一七主题中,它位于template-parts > post > content.php 中

WordPress function file Functions.php tutorial guide (super detailed)-WP-Host

预计阅读时间现在将出现在每个文章的标题中,并与日期一起显示。

4.删除WordPress版本号

旧版本的WordPress可能包含恶意黑客和机器人可以利用的安全漏洞。避免这种风险的一种方法是隐藏您的网站使用的 WordPress 版本。这被称为通过默默无闻的安全。

在我们继续之前,重要的是要注意,默默无闻不应该是您唯一的安全措施。这更像是为您已经安全的WordPress堡垒添加一个额外的堡垒。

隐藏您的版本号只需要您将以下非常简单的代码片段添加到函数文件中:

remove_action('wp_head', 'wp_generator');

现在将从您网站的所有区域中删除版本号,包括其代码和您的RSS提要。

5. 自动更新您的版权声明

更新版权声明中的年份是很容易忘记的小任务之一。你可以跟上的一种方法是使用这个技巧,它会根据你第一篇文章的发表年份自动生成版权日期。

将以下代码粘贴到您的函数文件中:

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;
}

然后在要显示版权信息的任何位置添加以下代码:

<?php echo wpb_copyright(); ?>

您现在将在您的网站上看到动态更新的版权日期。

WordPress function file Functions.php tutorial guide (super detailed)-WP-Host

在本例中,我们将日期添加到footer.php文件中,以便将其显示在页面底部。

6. 添加自定义菜单

大多数主题都有预定义的导航菜单,但如果您想创建自己的菜单并将其放置在网站上的任何位置,该怎么办?您需要做的就是将此代码粘贴到您的函数文件中:

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

您可以将“我的自定义菜单”替换为您要为菜单命名的名称。如果您转到管理区域中的外观 > 菜单,您应该会看到列出的新选项。

WordPress function file Functions.php tutorial guide (super detailed)-WP-Host

您现在可以在站点的任何位置添加新菜单。

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

最常见的是,您需要将此代码放在header.php文件中。

7. 自定义您的摘要

摘要是您文章的简短示例描述,可以显示在您的主页或搜索结果中,而不是完整的文章内容。默认情况下,所有摘录都具有相同的长度和链接文本,但您可以更改它。

首先,让我们更改将您从摘要带到完整文章的链接的文本。这通常是“阅读更多”或“继续阅读”,但您可以通过将以下代码段粘贴到您的函数文件中来制作任何您想要的内容:

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');

这里的链接文本已设置为Read the full article…

WordPress function file Functions.php tutorial guide (super detailed)-WP-Host

然后,让我们更改摘要的长度。将此代码粘贴到您的函数文件中:

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

默认情况下,标准长度为55个字。在本例中,它被设置为20。您可以将数字更改为您想要的任何值。

8. 为您的网站添加随机背景

最后,让我们以一个有趣的设计技巧结束。此调整使您可以在每次有人访问网站时为您的网站随机生成新的背景颜色。首先将以下代码添加到函数文件中:

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;
}

此代码为颜色生成HTML标记,因此您现在需要做的就是确保将其应用于页面。为此,您需要找到 <body> 标签,它应该如下所示:

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

这通常位于header.php文件中,但也可以在其他地方,具体取决于您的主题。找到正确的行后,只需将其替换为以下代码:

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

立即保存您的文件并打开您的网站。您应该会看到它具有新的背景颜色。

WordPress function file Functions.php tutorial guide (super detailed)-WP-Host

重新加载页面,您每次都会看到一种新颜色。

WordPress function file Functions.php tutorial guide (super detailed)-WP-Host

这显然不是每个网站的正确设计选择,但对某些网站来说这是一个巧妙的技巧。

小结

WordPress网站主题的functions.php文件是开始学习如何修改站点默认功能的理想场所。这是一个功能强大的文件,一旦您了解它的工作原理,您就可以对其进行大量控制。

WordPress Hosting / 悦然wordpress建站

WordPress Hosting / 悦然wordpress建站

【WordPress Hosting / 悦然wordpress建站】I am a WordPress hobby from China, and I like to communicate with friends from all over the world to learn WordPress website building and maintenance related knowledge.