Файл functions.php для WordPress неоднократно упоминался в данном блоге при решении тех или иных задач. Однако при этом я говорил о нем вскользь, подразумевая, что вы хорошо знакомы с его работой. Сегодня же наоборот, решил детально рассмотреть все нюансы, которые касаются файла функций functions.php: зачем он вообще нужен, как правильно и безошибочно с ним работать и т.п. Инструмент на самом деле весьма актуальный как при работе с админкой, так и в процессе редактирования темы. Пусть информация и немного теоретическая, почитать будет полезно (особенно новичкам).
Статья имеет 3 подраздела:
- Особенности и задачи functions.php;
- Редактирование файла функций;
- Типовые ошибки и примеры использования.
Что такое файл functions.php и зачем он нужен?
Как правило, в данном файле задаются дополнительные функции для шаблона, позволяющие менять внешний вид вашего сайта. Однако на самом деле его возможности значительно шире, поскольку functions.php в WordPress автоматически загружается при инициализации системы. То есть при вызове любой страницы, как фронтенда (сайта), так и бэкенда (админки), соответствующие функции из данного файла будут выполнены.
Следовательно, с помощью файла functions.php вы можете решить целый спектр абсолютно разных задач:
- Наиболее простой вариант — изменение внешнего вида темы. Вспоминаются сразу хаки для ссылки читать далее где можно влиять на вид линка «read more» и формат анонса.
- Определение своих функций дабы позже вызывать их в других файлах шаблона, что экономит время на внедрение изменений на сайте (да, и вообще является нормальным принципом в программировании). Например, функция отображение первой картинки поста, которую после определения можно использовать в файлах темы для категорий, тегов, архивов.
- Настройка админки под себя — скрытие определенных пунктов из меню, изменение разных параметров отображения для других пользователей и т.п. Сразу вспоминается статья про скрытие custom fields для не админов. Также с помощью functions.php в WordPress можно создать специальную страницу настроек темы.
- Переопределение каких-то параметров системы — изменение размеров миниатюр для шаблона, а также разного рода хаки и фильтры. Например, с помощью данного файла можно подправить отображение комментариев в wp_list_comments.
Вообще файл functions.php в WordPress по логике и скорости работы напоминает плагины. Хотя при этом у них есть принципиальные отличия. Модули используются, как правило, для решения каких-то конкретных задач и применяются к любой теме вашего сайта. Плюс для работы их нужно активировать. Что касается файла шаблона functions.php, то он может содержать много разных функций и выполняется только для той темы, в которой определен. То есть при смене шаблона, все ваши текущие наработки будут отключены, а система начнет считывать информацию из другого файла функций (об этом следует помнить).
Где находится functions.php и как его редактировать?
Файл функций расположен в корневой директории темы (вместе с index.php, single.php и другими). То есть вы заходите в папку wp-content/themes/название_темы/, и он будет там. Это не то же самое что одноименный файл ядра, который находится в системной директории /wp-includes/, нужный нам объект — в папке шаблона.
Сейчас в WordPress файл шаблона functions.php можно найти в 99% популярных тем, но раньше он был не везде. Если в вашей теме нет functions.php, то вы спокойно можете его создать.
Есть два способа редактирования файла функций:
- через WP админку;
- с помощью текстового редактора.
Первый вариант достаточно простой и наглядный. Вы заходите в меню «Внешний вид» — «Редактор» и выбираете соответствующий файл для правки.
После внесения изменений нажмите кнопку «Обновить файл» в самом низу. Преимущество данного метода в том, что вам не нужно использовать какие-то дополнительные программы для работы, все происходит внутри панели администрирования. Однако не всегда это возможно сделать.
Если файл functions.php закрыт для записи, то воспользоваться встроенным редактором WordPress у вас не получится. В таком случае запускаете FTP клиент, например, Mozilla и скачиваете файл функций на локальный компьютер.
Для работы с php файлом советую использовать специальные бесплатные редакторы — Notepad++ или Sublime Text. При этом важно чтобы кодировка редактируемого файла была UTF-8 без BOM. Вот как можно ее выбрать в Notepad++:
Если этого не сделать, то из-за BOM может возникнуть глюк в WordPress. Для Sublime Text 2 в меню «File» есть опция «Reopen With Encoding», позволяющая открыть файл в нужной кодировке. Однако при запуске functions.php автоматически срабатывает UTF-8 (т.к. файл сохранен именно в ней), поэтому ничего дополнительно делать не нужно.
После внесения изменений в файл, загружаете его обратно на FTP в ту же самую корневую папку активного шаблона. Второй метод, как видите, чуть более сложный, но иногда без него не обойтись. Если вдруг, редактируя functions.php в WordPress админке вы допустили ошибку, то весь сайт может перестать работать (увидите белый экран). В таком случае исправить код можно будет лишь, скачав файл функций на локальный компьютер и отредактировав его в текстовом редакторе.
Вставка сниппетов (примеры кода и типичные ошибки)
Дабы у вас не возникало ошибок при работе с functions.php в WordPress, давайте рассмотрим основные правила вставки кода и возможные ошибки. Первым делом обратите внимание на глобальную структуру любого PHP файла:
<?php // .... разный PHP код и функции .... ?>
Здесь в начале идет специальный открывающий тег и в конце закрывающий. Важно чтобы не было никаких пробелов перед открывающимся и после закрывающегося тегов! Хотя в некоторых случаях вы можете встретить запись, когда последнего тега нет (для PHP это нормально). Давайте рассмотрим парочку примеров.
Ситуация 1
Допустим, вы нашли в интернете готовый сниппет для решения определенной задачи. И в описании сказано, что нужно вставить этот код в файл функций functions.php. В качестве примера выберем код удаления WP версии из wp_head:
<?php remove_action('wp_head','wp_generator'); ?>
Так размещать неправильно:
<?php // .... разный PHP код и функции .... <?php remove_action('wp_head','wp_generator'); ?> ?>
Возникает ошибка, поскольку система встречает тег открытия <?php нового PHP блока без закрытия предыдущего. Логичнее просто опустить <?php … ?> из найденного сниппета (так правильно):
<?php // .... разный PHP код и функции .... remove_action('wp_head','wp_generator'); ?>
Следующий вариант также будет работать (между PHP блоками не должно быть пробелов):
<?php // .... разный PHP код и функции .... ?><?php remove_action('wp_head','wp_generator'); ?>
Ситуация 2
Допустим вы хотите обновить jQuery в WordPress для чего нашли соответствующий код:
function my_update_jquery () { wp_deregister_script('jquery'); wp_register_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js', false, false, true); wp_enqueue_script('jquery'); } add_action('wp_enqueue_scripts', my_update_jquery);
Неправильный вариант использования:
<?php // .... разный PHP код и функции .... ?> function my_update_jquery () { wp_deregister_script('jquery'); wp_register_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js', false, false, true); wp_enqueue_script('jquery'); } add_action('wp_enqueue_scripts', my_update_jquery);
Нельзя размещать код после закрывающего PHP тега. Вам нужно поставить всю функцию внутрь конструкции:
<?php // .... разный PHP код и функции .... function my_update_jquery () { wp_deregister_script('jquery'); wp_register_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js', false, false, true); wp_enqueue_script('jquery'); } add_action('wp_enqueue_scripts', my_update_jquery); ?>
Кстати, если в functions.php закрывающего тега ?> нет (что допускается), то добавляете нужный сниппет просто в конец файла.
Ситуация 3
Нельзя вставлять сниппет внутрь другой функции. Допустим, в файле шаблона functions.php у вас имеется следующий код:
<?php // .... разный PHP код .... function some_name() { // Открывающий тег функции // разный код внутри функции } // Закрывающий тег ?>
Неправильный вариант вставки:
<?php // .... разный PHP код .... function some_name() { // разный код внутри функции function my_update_jquery () { wp_deregister_script('jquery'); wp_register_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js', false, false, true); wp_enqueue_script('jquery'); } add_action('wp_enqueue_scripts', my_update_jquery); } // Закрывающий тег ?>
Добавить код можно только после закрывающего тега «}» первой функции. Вот так будет правильно:
<?php // .... разный PHP код .... function some_name() { // разный код внутри функции } // Закрывающий тег function my_update_jquery () { wp_deregister_script('jquery'); wp_register_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js', false, false, true); wp_enqueue_script('jquery'); } add_action('wp_enqueue_scripts', my_update_jquery); ?>
Ситуация 4
Рассмотрим для ознакомления еще один вариант, когда внутри функции вы можете встретить конструкцию <?php … ?>, которая не будет нарушать общий порядок работы самого файла.
<?php // .... разный PHP код .... function oxygen_metabox() { $oxygen_post_location = get_post_meta( $post->ID, '_oxygen_post_location', true ); ?> <p><?php echo __( 'Featured', 'oxygen' ) ?></label></p> <span class="description"><?php _e( 'Post location on the home page', 'oxygen' ); ?> <?php } // .... разный PHP код .... ?>
Тут нужно учитывать 2 нюанса. Во-первых, не должно быть ошибок в последовательности открывающих и закрывающих PHP тегов — каждый открытый блок должен быть закрыт. Во-вторых, внутри функции {…} пробелы и переносы строк между тегами <?php и ?> не критичны. В любом случае нужно быть очень внимательным в процессе редактирования. Плюс редакторов Notepad++ и Sublime Text в том, что они подсвечивают теги/функции, и так проще ориентироваться в коде.
Итого. Надеюсь, данное руководство по WordPress файлу functions.php вам пригодится. Данный инструмент в веб-разработке под WP весьма и весьма полезен. Нужно только внимательно с ним работать, так как ошибки могут привести к проблемам в работе сайта. Дабы ничего не нарушить я предпочитаю редактировать файл через текстовые редакторы, предварительно сохранив оригинальный вариант на всякий случай.
Если у вас остались вопросы по работе с functions.php в вордпресс, пишите их в комментариях.
P.S. Постовой. Продвижение и оптимизация сайта — важные знания для вебмастеров.
А вы знаете самые популярные сайты? — ТОП10 сайтов в мире (по посещаемости).
Вступление: Здравствуйте! Один из важнейших файлов вашей рабочей темы является файл functions.php
WordPress. Любой администратор сайта обязан знать назначение этого файла и правила работы с ним.
Файл functions.php
не нужно создавать. Он создан разработчиком темы и включён в каталог темы. Работает файл, как плагин и активируется с активацией выбранной вами темы.
Написан файл functions.php
на языке программирования PHP, с использованием функций и тегов разработанных для CMS WordPress.
Где находится файл functions.php?
Файла functions.php
(файл функций) находится в папке вашей рабочей темы. Чтобы его найти откройте корневую папку вашего сайта. В нём откройте каталог wp-content
, далее каталог themes
. Теперь, открыв каталог с названием вашей рабочей темы вы найдёте файл functions
. Однако не торопитесь его редактировать. Напрямую лучше этого не делать.
Ещё раз обращу ваше внимание: файл функций есть в любой теме WordPress. Он не является шаблонным. Каждый разработчик специально пишет его для своей темы. Однако вы можете его редактировать добавляя новые и изменяя старые возможности вашей темы (о редактировании чуть ниже).
Как редактировать файл functions.php WordPress?
В Интернет вы легко найдёте куски кодов php
, которые нужно добавить в файл функций, чтобы изменить и дополнить функционал темы.
Структура этих кодов узнаваемо проста: в начале идёт function, далее название функции, далее код. В конце кода могут быть: add_action
(хук действия) add_filter
(хук фильтра).
Теоретическое использование подобных функций довольно простое. Вам нужно проверить код на правильный php
синтаксис (это можно сделать тут: phpcodechecker.com) и вставить в файл functions.php
.
Однако напрямую вставлять новую функцию в файл функций рабочего проекта я вам не рекомендую, и вот почему.
Во-первых, неправильный код или его неправильная вставка непосредственно в файл функций могут «убить» ваш сайт.
Примечание: Проблемы с доступностью сайта в результате ошибок на WordPress принято называть «Белый экран смерти». Самое простое решение проблемы «белого экрана» наличие резервной копии сайта. Читать: Резервное копирование сайта WordPress. О более сложных решениях поговорим в следующих статьях.
Ещё раз обращу ваше внимание: самая простая ошибка в коде в виде пропущенной точки с запятой, может заставить весь ваш сайт исчезнуть.
Во-вторых, если вставляемый код правильный и начнёт работать, он исчезнет после первого обновления вашей темы.
В-третьих, если вы смените тему все ваши новые добавленные функции перестанут работать.
Как правильно редактировать файл functions.php?
Есть два правильных варианты редактирования (добавления функций) файла functions.php
. Один простой, второй более сложный.
Простой вариант
Есть великолепный плагин под названием «Code Snippets», автор Code Snippets pro.
Установив его на сайт единожды, вы сможете редактировать файла functions.php
рабочей темы без выше перечисленных опасений. Как работать с этим плагином читайте в следующей статье.
Сложный вариант
Если вы используете дочернюю тему для своего сайта, то править файл функций можно без плагина Code Snippets.
Для этого создаёте в «дочке» файл functions.php
, можно пустой. Далее просто вносите свои новые функции (хуки) в этот файл.
Создать пустой файл просто. В файле должен быть открывающий тег PHP в начале и закрывающий тег PHP в конце. Между ними вы должны вставлять ваши новые функции.
Обратите внимание, что файл functions.php
«дочки» не подменяет такой же файл «родительской темы». В «дочке» он будет загружаться как дополнение к файлу функций родителя, но перед ним. Читать: Самый простой способ создать дочернюю тему.
Пример правки файла functions.php WordPress
Не все темы WordPress в customizer имеют настройки по фильтру рубрик, которые нужно показывать на главной странице последних записей. Это можно сделать с помощью такой функции с хуком фильтра. Вот она:
function exclude_cat($query) {
if ($query->is_home)
{$query->set('cat','-25, -46, -53, -70');} // где -25, -46, -53, -70
//это id убираемых категорий
return $query; }
add_filter('pre_get_posts','exclude_cat');
Итак, функция с хуком фильтра у нас есть. Теперь нужно проверить имеющийся код на синтаксис php
(адрес сервиса проверок выше).
Как видим ошибок нет. Далее нужно вставить этот код на сайт при помощи плагина Code Snippets.
После активации сниппета указанные в коде рубрики не будут показаны в блоге последних записей.
Заключение
В завершении статьи про файл functions.php
WordPress, дам две рекомендацию. Никогда не меняйте этот файл напрямую. Всегда имейте его базовую копию, а лучше свежую резервную копию всего сайта.
©wpkupi.ru
Еще статьи
Topics
- What is
functions.php
? - Examples
- Theme Setup
- Automatic Feed Links
- Navigation Menus
- Load Text Domain
- Post Thumbnails
- Post Formats
- Theme support in block themes
- Initial Setup Example
- Content Width
- Other Features
- Theme Setup
- Your functions.php File
Note: Functions.php
can be used by both classic themes, block themes, and child themes.
The functions.php
file is where you add unique features to your WordPress theme. It can be used to hook into the core functions of WordPress to make your theme more modular, extensible, and functional.
The functions.php
file behaves like a WordPress plugin, adding features and functionality to a WordPress site. You can use it to call WordPress functions and to define your own functions.
Note: The same result can be produced using either a plugin or functions.php
. If you are creating new features that should be available no matter what the website looks like, it is best practice to put them in a plugin.
There are advantages and tradeoffs to either using a WordPress plugin or using functions.php
.
A WordPress plugin:
- requires specific, unique header text;
- is stored in wp-content/plugins, usually in a subdirectory;
- only executes on page load when activated;
- applies to all themes; and
- should have a single purpose – for example, offer search engine optimization features or help with backups.
Meanwhile, a functions.php
file:
- requires no unique header text;
- is stored in theme’s subdirectory in wp-content/themes;
- executes only when in the active theme’s directory;
- applies only to that theme (if the theme is changed, the features can no longer be used); and
- can have numerous blocks of code used for many different purposes.
Each theme has its own functions file, but only code in the active theme’s functions.php
is actually run. If your theme already has a functions file, you can add code to it. If not, you can create a plain-text file named functions.php
to add to your theme’s directory, as explained below.
A child theme can have its own functions.php
file. Adding a function to the child functions file is a risk-free way to modify a parent theme. That way, when the parent theme is updated, you don’t have to worry about your newly added function disappearing.
Note: Although the child theme’s functions.php
is loaded by WordPress right before the parent theme’s functions.php
, it does not override it. The child theme’s functions.php
can be used to augment or replace the parent theme’s functions. Similarly, functions.php
is loaded after any plugin files have loaded.
With functions.php
you can:
- Use WordPress hooks. For example, with the
excerpt_length
filter you can change your post excerpt length (from default of 55 words). - Enable WordPress features with
add_theme_support()
. For example, turn on post thumbnails, post formats, and navigation menus. - Define functions you wish to reuse in multiple theme template files.
Warning:
In WordPress, naming conflicts can occur when two or more functions, classes, or variables have the same name. This can cause errors or unexpected behavior in a WordPress site. It is the responsibility of both the theme developer and plugin developer to avoid naming conflicts in their respective code.
Theme developers should ensure that their functions, classes, and variables have unique names that do not conflict with those used by WordPress core or other plugins. They should also prefix their function and class names with a unique identifier, such as the theme name or abbreviation, to minimize the chances of a naming conflict.
Below are a number of examples that you can use in your functions.php file to support various features. Each of these examples are allowed in your theme if you choose to submit it to the WordPress.org theme directory.
A number of theme features should be included within a “setup” function that runs initially when your theme is activated. As shown below, each of these features can be added to your functions.php
file to activate recommended WordPress features.
Note: It’s important to namespace your functions with your theme name. All examples below use myfirsttheme_
as their namespace, which should be customized based on your theme name.
To create this initial function, start a new function entitled myfirsttheme_setup()
, like so:
if ( ! function_exists( 'myfirsttheme_setup' ) ) :
/**
* Sets up theme defaults and registers support for various WordPress
* features.
*
* It is important to set up these functions before the init hook so
* that none of these features are lost.
*
* @since MyFirstTheme 1.0
*/
function myfirsttheme_setup() { ... }
Note: In the above example, the function myfirsttheme_setup is started but not closed out. Be sure to close out your functions.
Automatic feed links enables post and comment RSS feeds by default. These feeds will be displayed in <head>
automatically. They can be called using add_theme_support()
in classic themes. This feature is automatically enabled for block themes, and does not need to be included during theme setup.
add_theme_support( 'automatic-feed-links' );
In classic themes, custom navigation menus allow users to edit and customize menus in the Menus admin panel, giving users a drag-and-drop interface to edit the various menus in their theme.
You can set up multiple menus in functions.php
. They can be added using register_nav_menus()
and inserted into a theme using wp_nav_menu()
, as discussed later in this handbook. If your theme will allow more than one menu, you should use an array. While some themes will not have custom navigation menus, it is recommended that you allow this feature for easy customization.
register_nav_menus( array(
'primary' => __( 'Primary Menu', 'myfirsttheme' ),
'secondary' => __( 'Secondary Menu', 'myfirsttheme' )
) );
Each of the menus you define can be called later using wp_nav_menu()
and using the name assigned (i.e. primary) as the theme_location
parameter.
In block themes, you use the navigation block instead.
Themes can be translated into multiple languages by making the strings in your theme available for translation. To do so, you must use load_theme_textdomain()
. For more information on making your theme available for translation, read the internationalization section.
load_theme_textdomain( 'myfirsttheme', get_template_directory() . '/languages' );
Post thumbnails and featured images allow your users to choose an image to represent their post. Your theme can decide how to display them, depending on its design. For example, you may choose to display a post thumbnail with each post in an archive view. Or, you may want to use a large featured image on your homepage. This feature is automatically enabled for block themes, and does not need to be included during theme setup.
add_theme_support( 'post-thumbnails' );
Post formats allow users to format their posts in different ways. This is useful for allowing bloggers to choose different formats and templates based on the content of the post. add_theme_support()
is also used for Post Formats. This is recommended.
add_theme_support( 'post-formats', array( 'aside', 'gallery', 'quote', 'image', 'video' ) );
Learn more about post formats.
In block themes, the following theme supports are enabled automatically:
add_theme_support( 'post-thumbnails' );
add_theme_support( 'responsive-embeds' );
add_theme_support( 'editor-styles' );
add_theme_support( 'html5', array( 'style','script' ) );
add_theme_support( 'automatic-feed-links' );
Including all of the above features will give you a functions.php
file like the one below. Code comments have been added for future clarity.
As shown at the bottom of this example, you must add the required add_action()
statement to ensure the myfirsttheme_setup
function is loaded.
if ( ! function_exists( 'myfirsttheme_setup' ) ) :
/**
* Sets up theme defaults and registers support for various
* WordPress features.
*
* Note that this function is hooked into the after_setup_theme
* hook, which runs before the init hook. The init hook is too late
* for some features, such as indicating support post thumbnails.
*/
function myfirsttheme_setup() {
/**
* Make theme available for translation.
* Translations can be placed in the /languages/ directory.
*/
load_theme_textdomain( 'myfirsttheme', get_template_directory() . '/languages' );
/**
* Add default posts and comments RSS feed links to <head>.
*/
add_theme_support( 'automatic-feed-links' );
/**
* Enable support for post thumbnails and featured images.
*/
add_theme_support( 'post-thumbnails' );
/**
* Add support for two custom navigation menus.
*/
register_nav_menus( array(
'primary' => __( 'Primary Menu', 'myfirsttheme' ),
'secondary' => __( 'Secondary Menu', 'myfirsttheme' ),
) );
/**
* Enable support for the following post formats:
* aside, gallery, quote, image, and video
*/
add_theme_support( 'post-formats', array( 'aside', 'gallery', 'quote', 'image', 'video' ) );
}
endif; // myfirsttheme_setup
add_action( 'after_setup_theme', 'myfirsttheme_setup' );
In classic themes, a content width is added to your functions.php
file to ensure that no content or assets break the container of the site. The content width sets the maximum allowed width for any content added to your site, including uploaded images. In the example below, the content area has a maximum width of 800 pixels. No content will be larger than that.
if ( ! isset ( $content_width) ) {
$content_width = 800;
}
Themes that include a theme.json configuration file does not need to include the variable in functions.php. Instead, the content width is added to the layout setting in theme.json. You can learn more about using theme.json in the advanced section.
There are other common features you can include in functions.php
. Listed below are some of the most common features. Click through and learn more about each of these features.
- Custom Headers -Classic themes
- Sidebars (widget areas) -Classic themes
- Custom Background -Classic themes
- Title tag -Classic themes
- Add Editor Styles
- HTML5 -Classic themes
If you choose to include all the functions listed above, this is what your functions.php might look like. It has been commented with references to above.
/**
* MyFirstTheme's functions and definitions
*
* @package MyFirstTheme
* @since MyFirstTheme 1.0
*/
/**
* First, let's set the maximum content width based on the theme's
* design and stylesheet.
* This will limit the width of all uploaded images and embeds.
*/
if ( ! isset( $content_width ) ) {
$content_width = 800; /* pixels */
}
if ( ! function_exists( 'myfirsttheme_setup' ) ) :
/**
* Sets up theme defaults and registers support for various
* WordPress features.
*
* Note that this function is hooked into the after_setup_theme
* hook, which runs before the init hook. The init hook is too late
* for some features, such as indicating support post thumbnails.
*/
function myfirsttheme_setup() {
/**
* Make theme available for translation.
* Translations can be placed in the /languages/ directory.
*/
load_theme_textdomain( 'myfirsttheme', get_template_directory() . '/languages' );
/**
* Add default posts and comments RSS feed links to <head>.
*/
add_theme_support( 'automatic-feed-links' );
/**
* Enable support for post thumbnails and featured images.
*/
add_theme_support( 'post-thumbnails' );
/**
* Add support for two custom navigation menus.
*/
register_nav_menus( array(
'primary' => __( 'Primary Menu', 'myfirsttheme' ),
'secondary' => __( 'Secondary Menu', 'myfirsttheme' ),
) );
/**
* Enable support for the following post formats:
* aside, gallery, quote, image, and video
*/
add_theme_support( 'post-formats', array( 'aside', 'gallery', 'quote', 'image', 'video' ) );
}
endif; // myfirsttheme_setup
add_action( 'after_setup_theme', 'myfirsttheme_setup' );
If you’re just getting started with WordPress development, one of the most important files you should familiarize yourself with is the functions.php file. There are actually three possible functions.php files that you might use on your WordPress website, and each plays a different role. Knowing where these files live, what their purpose is, and how and when to modify them will help you when troubleshooting issues and give you more control over your site’s functionality.
In this article, we’ll cover everything you need to know about WordPress functions.php files. You’ll learn what functions.php does and how to find and edit it. We’ll even include a few useful code snippets to try out.
You can start at the beginning and read through or jump to a specific section using the table of contents below:
- What is functions.php in WordPress?
- Where is the functions.php file located?
- How to access functions.php
- Accessing functions.php in your WordPress Admin Interface
- Accessing functions.php via FTP
- Accessing functions.php in your cPanel
- When should I edit functions.php in WordPress?
- How to edit functions.php in WordPress
- Editing functions.php in your WordPress Theme File Editor
- Editing functions.php with a text editor
- Editing functions.php directly in cPanel
- Using a plugin to add functions to your WordPress site
- How to protect functions.php from security exploits
- What code can I add to functions.php in WordPress?
- FAQ
- Do I need to create a child theme to edit functions.php?
- How do I restore functions.php from a backup if I don’t have access to my WordPress dashboard?
- Can I add JavaScript to my functions.php file?
What is functions.php in WordPress?
In WordPress, the functions.php file is where vital code lives that determines the way your site works. There are actually at least two functions.php files in every WordPress website — one included with WordPress core and one included with your theme. If you’re using a child theme, you should also have a functions.php in your child theme folder.
The functions.php file in WordPress core contains important code that’s required for WordPress to function. You should almost never modify the code in WordPress core’s functions.php file.
Your theme’s functions.php file is where all the theme-specific features of your website live — like custom menu locations, widget areas, custom header and footer content and functionality, post excerpt length, and more.
Your theme’s functions.php file behaves in much the same way as a WordPress plugin. The difference is that functions.php should be used for code that is theme-specific, while plugins should be used for functionality that will remain even when you switch themes.
Where is the functions.php file located?
We’ve talked about what the functions.php file does both in WordPress core and in the theme files, but how do you find the functions.php file? Where is functions.php in WordPress?
All of your WordPress files are located in your site’s root directory and in various subfolders. Your root directory is usually named something like public_html or www, but may have a different name. If you aren’t sure where to find your WordPress installation folder on your server, contact your web host.
Once you’ve found where your WordPress files are located on your server, you can start looking for your functions.php files. We’ve mentioned that there are up to three locations for functions.php: WordPress core, your theme folder, and your child theme folder. In this section we’ll go over where to find each one.
Where is functions.php in WordPress core?
If you’re looking for the location of functions.php in WordPress core, you’ll find it in the wp-includes folder of your WordPress installation.
While you should never edit functions.php in WordPress core, you may find yourself needing to inspect it for one reason or another. The most likely scenario for poking around in functions.php in WordPress core is if you suspect that malware has been injected into it.
Before even opening functions.php, you should make a backup of your WordPress site in case you accidentally make a change to the file that causes a critical error. If you find that functions.php has been corrupted or hacked, chances are you may have other areas of WordPress that are affected. The best thing to do is simply replace WordPress with a fresh installation, rather than trying to remove all the offending scripts one-by-one.
Where is functions.php in my WordPress theme folder?
Your theme’s functions.php file is located in the main directory of your theme folder: wp-content → themes → yourtheme.
Where is functions.php in the WordPress child theme folder?
The WordPress child theme functions.php file is located in the main directory of your child theme folder: wp-content → themes → yourtheme-child.
How do I access functions.php?
Knowing where to find functions.php is only half the job. Now comes the question of how to access functions.php in WordPress. While the functions.php file in WordPress core can only be accessed through secure file transfer protocol (SFTP) or through cPanel, your theme and child theme functions.php files can also be accessed in the WordPress Theme File Editor.
Accessing functions.php in the WordPress Theme File Editor
If you need to access your theme or child theme’s functions.php file, you can do so directly from the WordPress Theme File Editor. In your WordPress dashboard, go to Appearance → Theme File Editor.
You’ll be taken to the Edit Themes page. From here, under the dropdown next to Select theme to edit, choose your theme and click Select. You’ll see a list of files available to edit under the Theme Files column at the far right of your screen. Click functions.php to open the file.
If you’re in your parent theme’s functions.php file, you’ll see a warning notice on the bottom of the screen above the Update File button that says, “Caution: This is a file in your current parent theme.”
Note: If you’re not the theme developer, you should make your changes in your child theme’s functions.php file to avoid having your edits overwritten in future theme updates.
Accessing functions.php via SFTP
Step 1: Install your SFTP client. If you don’t have an SFTP client already, you’ll need to download one. There are some great free and premium options out there, including:
Application | System | Free or Premium |
WinSCP | Windows | Free |
Filezilla | Windows, Mac, Linux | Free and premium options |
Cyberduck | Windows, Mac | Free |
Transmit | Mac | Premium |
In this example, we’ll be using Filezilla. Other SFTP clients should work in a similar fashion.
Step 2: Retrieve your SFTP credentials. To log into your server via SFTP you’ll need the following details:
- Host (your server’s IP address or url)
- SFTP username
- Password
- Port number
These details can usually be found in your hosting control panel. This information might be generated for you or your host may prompt you to create an SFTP username and password. If you don’t know where to find these credentials or have trouble figuring out how to create them, search your host’s help documentation for instructions or contact their support team.
Step 3: Enter your SFTP credentials.
Enter your host’s IP address or url, your SFTP username, password, and the port number (usually 22 or 2222, but some hosts may use a different port).
Note: You might get a ‘host key unknown’ alert if your SFTP client uses trust on first use (TOFU) authentication. Check ‘Always trust this host, add this key to the cache’ if you plan on using your SFTP client to access the site again. Click OK to proceed.
Step 4: Navigate to your website’s root directory.
Once you’ve logged in, you’ll see two file trees displayed at the button of your screen — one on the left and one on the right. The right side lists the directories on your web server (remote). The left side lists the directories on your computer (local).
Your root directory is usually in a folder labeled www or public_html, but it might use a different name. If you aren’t sure what folder to look in, ask your hosting provider. You’ll know you’re in the correct folder if you see the wp-admin, wp-content, and wp-includes folders near the top of your file list.
Step 5: Navigate to functions.php in WordPress core, your parent theme, or child theme. If you’re looking for functions.php in WordPress core, you’ll navigate to the wp-includes folder.
If you’re looking for functions.php in your theme directory, you’ll navigate to wp-content → themes → yourtheme.
To find your child theme’s functions.php file, go to wp-content → themes → yourtheme-child.
Step 6: Download functions.php. Now that you know where functions.php is located and have accessed it, you might want to inspect or edit the file. Before you can do that, you’ll need to download it. Right click on your functions.php file and select Download. Your file will be downloaded to your local machine.
Accessing functions.php in cPanel
If your host uses cPanel, you can access functions.php through its file manager. If you don’t know how to find cPanel in your host’s dashboard, contact their customer support for help.
Step 1: Open cPanel’s File Manager. Once you’re in cPanel, navigate to the Files section and click on File Manager.
Step 2: Open your website’s root folder. The root folder is commonly called www or public_html, but it may have another name. Root folder naming conventions differ on some hosts, so if you aren’t sure what folder to look in, ask your hosting provider.
You’ll know you’re in the correct folder if you see the wp-admin, wp-content, and wp-includes folders near the top of your file list.
Step 3: Find and download functions.php. The functions.php file for WordPress core is located in your wp-includes folder.
Your theme’s functions.php file is located in wp-content → themes → yourtheme.
If you’re looking for your child theme’s functions.php file, you can find it in wp-content → themes → yourtheme-child.
When you’ve found the functions.php file you’re looking for, right click on functions.php and click Download, or single-click functions.php and then click the Download option from the top menu.
If you rename your file when you save it, make sure to name it back to functions.php before re-uploading it. And before you make changes to and overwrite functions.php, back up your WordPress site.
When should I edit functions.php in WordPress?
Before we dive in to how to edit functions.php, we should talk about if and when you should edit it. There are many reasons you might want to edit PHP code in WordPress, but adding that code to your functions.php file is not always the best option and should only be done under certain circumstances, which we’ll discuss below.
When to edit functions.php in WordPress core
Never. You shouldn’t edit functions.php in WordPress core. At most, you might replace it if you find that it’s been corrupted, but deleting or adding code to WordPress core functions.php is likely to break your site. So, you can open it, inspect it, replace it with a fresh copy if you need to, but don’t mess around on any live websites.
When to edit functions.php in your theme
When it comes to your theme’s functions.php file, you may or may not need to edit it. If you’re creating your own theme, you’ll most certainly want to add some custom code to functions.php. Just about every theme has code in its functions.php file that gives it a unique set of features and capabilities. Besides your stylesheets, these functions are a huge part of what makes one theme different from another.
If you’re adding code to your theme’s functions.php file that isn’t specific to your theme and could be used independently of your theme, consider making it a plugin instead. This way you can use that feature across multiple themes and even submit it to the WordPress.org plugin library where it might benefit other WordPress users.
Before creating your plugin, check the plugin library to make sure what you’re creating doesn’t already exist. If a quality solution exists already, you might want to save your development energy for a different custom feature on your site.
When to edit functions.php in your child theme
If you’re using a theme from a developer, and want to modify the functions.php file, you should always use a child theme to make those changes. When theme developers issue a new version of their theme and you update to the latest one, your current theme is overwritten by the new files — including functions.php.
Child themes are unaffected by parent theme updates, so you’ll retain all your custom code if you make changes in a child theme’s functions.php file.
Before adding code, consider whether using a plugin would be a better solution. Is the code you’re adding specific to your theme? Edit your child theme’s functions.php file. Is the code you’re adding something you want to still have if you change themes in the future (e.g. Google Analytics tracking code or Facebook pixel)? Use a plugin.
How to edit functions.php in WordPress
You should always take steps to protect your site from any mistakes you might make while editing functions.php. So before you start making edits, back up your site and consider creating a staging site to test them first. This way your live site is not disrupted if you accidentally add some code to functions.php that causes major issues or — even worse — crashes your site completely.
Now that you’ve backed up your site, you can move on to editing your functions.php file.
How to edit functions.php in the WordPress Theme File Editor
Editing functions.php in the WordPress Theme File Editor is a little risky. If you’re using this tool because you don’t have access to cPanel or SFTP, then you’ll be in a pretty bad situation if your edits cause a fatal error that prevents you from accessing your WordPress dashboard.
If you want to edit functions.php in the Theme File Editor, make sure that you have direct access to the server and your backups so you can restore your backup file quickly.
You can find the WordPress Theme File Editor under Appearance → Theme File Editor in your WordPress admin panel.
You’ll be taken to the Edit Themes screen, where you should select your child theme, then select the functions.php file from the Theme Files column at the right of your screen.
If you’ve selected the parent theme instead, you’ll see a warning at the bottom of your screen that says, “Caution: This is a file in your current parent theme.” You don’t want to make edits to your parent theme’s functions.php file because your changes will be overwritten the next time you update your theme.
If you see functions in your file that you don’t understand, WordPress includes a handy documentation lookup feature just above the Update File button. Click the dropdown and search for the function name that you want to learn more about and click Look Up. You’ll be directed to the WordPress.org documentation for that function.
When you’re done with your changes, click Update File. Check the front and back end of your site to make sure everything is still working as intended. If you encounter a fatal error and need to restore functions.php from your backup, you can do that in cPanel or via SFTP.
Editing functions.php with a text editor
The best way to edit functions.php is in your code editing software of choice. Since you’re editing a copy that’s offline on your local computer, you don’t have to be connected to the internet to work on your file. You’ll also have more control over when you commit your changes to your live site.
You can edit your code whenever you like and upload your changes at a time when your website normally gets the least traffic. That way, if there are any issues, the fewest number of visitors will be impacted.
Step 1: Open functions.php in your text editor. If you aren’t familiar with using a text editor, there are several free options to choose from.
Free source code and plain text editors:
Application | System |
Notepad++ | Windows |
Atom.io | Windows, Mac, Linux |
Sublime | Windows, Mac, Linux |
TextEdit *make sure you’re in plain text mode |
Mac (default application) |
Notepad | Windows (default application) |
Step 2: Edit functions.php and save to your local machine. Your display may look different depending on what program you use to edit your functions.php file. This is what PHP code looks like in atom.io:
Add or change whatever information you need to, then save your file.
Step 3: Log into your web server via SFTP or cPanel. Navigate to your theme or child theme folder and find the functions.php file.
Step 4: Change the file name of functions.php on your web server. In case your edited version contains errors, you don’t want to overwrite your original functions.php file. You’ve made a backup, of course, but instead of having to pull the functions.php file from your backup, you’ll have your original file on-hand.
You want to be able to restore the functions.php file quickly if something goes wrong, so renaming it to something like ‘functions-orginal.php’ will make sure that the contents of the original file are preserved on your server.
Step 5: Upload functions.php from your local machine to your webserver. Using SFTP or cPanel, upload your functions.php file to your theme or child theme’s main directory.
Step 6: Visit your website to make sure it’s working correctly. Once you’ve uploaded your functions.php file, you should check to make sure that everything is working on your site. Visit the front end and log in to the WordPress dashboard to make sure everything is accessible and displays and functions correctly.
Step 7: Delete the old, renamed functions.php file. Once you’ve established that your site is working properly, you can delete functions-original.php (or whatever you renamed it to). If you find an issue down the road, you should still have your functions.php file from the backup you made.
Editing functions.php directly in cPanel
If you don’t have or don’t want to use a source code editor, you can edit functions.php directly in cPanel (if your host uses cPanel). Like editing in the WordPress Theme File Editor, it’s a little more risky than working on your local machine. If your internet connection is disrupted while you’re editing, you could lose your changes. You also run the risk of potentially overwriting your original functions.php file.
Step 1: Find functions.php in cPanel. In cPanel, click on File Manager.
Navigate to your root folder (usually public_html or www, but it could have a different name).
Step 2: Make a copy of functions.php. In your File Manager main menu, click + Folder to add a new folder. You’ll want to make a copy of your functions.php file and save it here as a backup.
Name your new folder something easy to identify like ‘backup functions’ so you can easily find it later. Click Create New Folder.
Step 3: Find functions.php in your theme or child theme folder and copy it to the backup folder. In your theme or child theme folder, scroll down to functions.php and right click on the file name. Select Copy.
A dialog box will appear asking you to enter the path you want to copy the file to. The path to the folder you’re currently in will be pre-populated, so if the file path to your backup folder differs from what you see, type in the correct path. Click Copy File(s).
Step 4: Navigate back to functions.php in the theme or child theme directory. Now that you have a backup, you can go back to the functions.php file in the theme or child theme directory and start editing.
Right click on functions.php, then click Edit.
Step 5: Edit functions.php. You should now see the contents of your functions.php file on your screen. It should look something like this:
Add or change whatever information you need, then save your file.
Using a plugin to add functions to your WordPress site
Instead of directly modifying the functions.php file, you can use a plugin like Code Snippets to add functions to your website. If you need to add a fair number of functions to your site, it can be easy to lose track of which functions you still need and which you don’t.
Code Snippets provides a graphical user interface (GUI) for managing your blocks of PHP code. You can add descriptions so that you know what the code is supposed to do, and turn blocks of code on and off, much like activating and deactivating a plugin.
Since you’re not making changes to functions.php, it’s a much safer method of adding PHP functions to your WordPress site.
How to protect functions.php from security exploits
The functions.php file is often a target of hackers, so keeping it safe should be a high priority. Take the following steps to help you secure your functions.php file:
1. Install a security plugin
By using a security plugin, you’ll enjoy advanced protection from hackers across multiple areas of your site.
Jetpack Security is an inexpensive option that helps keep your site safe from malicious attacks. It includes malware scanning and one-click fixes, brute force attack protection, downtime monitoring, an activity log so you know if and when your site was hacked, and login protection via two-factor authentication (2FA).
Jetpack Security also monitors your site for any changes to core WordPress files, outdated or insecure plugins, and other vulnerabilities so that you can catch them before a hacker finds them and takes advantage.
Plus, it provides real-time WordPress backups so you can quickly restore a clean version if anything goes wrong — even if you can’t log into your site.
2. Deny access to WordPress core functions.php via the .htaccess file
If your website is hosted on an Apache server, you can use an .htaccess file to help protect your WordPress core functions.php file by blocking access to the entire wp-includes folder.
Step 1: Download .htaccess
Using SFTP or cPanel, navigate to the root folder of your website. Right click on .htaccess and select Download to download the file to your local computer.
Step 2: Add code to block access to the wp-includes folder
In a source code or plain text editor, open .htaccess and add the following code:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^wp-admin/includes/ - [F,L]
RewriteRule !^wp-includes/ - [S=3]
RewriteRule ^wp-includes/[^/]+.php$ - [F,L]
RewriteRule ^wp-includes/js/tinymce/langs/.+.php - [F,L]
RewriteRule ^wp-includes/theme-compat/ - [F,L]
</IfModule>
Save your file. Make sure that your editor program does not include a file extension. If you’re using Notepad++ or Text Edit, it may add a .txt file extension. The file should simply be named ‘.htaccess.’
Step 3: Upload the edited .htaccess back to the root folder
Upload your edited .htaccess file back to your website’s root folder. You’ll be asked if you want to overwrite the existing file. Click Ok.
Now your .htaccess file should block external access to any files in your wp-includes folder, including functions.php.
3. Deny access to functions.php using functions.php
You can block direct access to your functions.php file by adding the following code snippet directly to functions.php.
if (!empty($_SERVER[‘SCRIPT_FILENAME’]) && ‘functions.php’ ==
basename($_SERVER[‘SCRIPT_FILENAME’]))
{
die (‘Access denied!’);
}
4. Hide functions.php outside of the root directory
Hackers know the default location of all standard WordPress files. Changing the location of sensitive files to a restricted access folder outside the root directory can keep it out of reach of hackers. This process is a little more involved than just adding some code to your .htaccess file, but it’s worth the extra effort for the additional layer of protection to your website.
In just a few steps, you can secure functions.php outside of the root folder.
Step 1 : Download your current functions.php file
If you’re moving your theme’s functions.php file, you’ll find it under wp-content → themes → yourtheme. Your child theme’s file will be in wp-content → themes → yourtheme-child.
Once you’ve found your functions.php file, download it to your computer via SFTP or cPanel.
Step 2 : Create a new directory outside of the root folder
Navigate outside of your root directory to the next file folder level up. You should see the name of your root folder as well as several other folders. In this directory, right click and select Create directory.
Give your directory a name that’s easy to remember as the location of your functions.php file.
Step 3: Upload functions.php to your new folder
Upload the functions.php file you downloaded earlier into your new folder via SFTP or cPanel.
Check your new folder and functions.php file permissions and make sure they’re set to 600.
Step 4 : Point WordPress to the new functions.php file
You should have a functions.php file in your new directory as well as the original functions.php file that is still in your theme folder. In order for WordPress to find and use the correct file, you’ll want to delete all the information in your theme file’s functions.php file and the following code snippet:
<?php
include('/home3/usr/securefunctions/functions.php');
?>
Note: Your file path will look different, as you’ll be using your server’s directory names.
In cPanel, you can open the root directory’s functions.php file and edit it directly or you can edit the copy you downloaded to your local machine earlier using a source code editor. For this example, we’ve edited the copy we downloaded earlier using Atom.io.
Save your funtions.php file and upload it back to your theme directory.
You’ll be asked if you want to overwrite the file. Click Ok.
Now, WordPress should reference your new functions.php file in its secure location outside of the root folder.
4. Change the name of your functions.php file
Changing the name of your functions.php file is another step you can take to keep it safe from hackers. You’ll need to host this file outside of your root folder, so if you’ve followed the process in Hide functions.php outside of the root directory, you’ll only need to take a few additional steps.
Step 1: In your secure directory outside the root folder, change the file name of functions.php
Go to the functions.php folder hosted outside of your root directory and change the file name to something unique, like ‘keep-out.php’ or ‘these-are-not-the-functions-you-are-looking-for.php’. Okay, that last one’s a little long, but it doesn’t really matter what you call it as long as you include it in the file path in the theme folder copy of functions.php.
Step 2: Edit the code in functions.php in your root directory to reflect the name change
Now that you’ve changed the name to something other than functions.php, you’ll need to make sure your theme directory copy of functions.php is pointing to the right file name.
Download the root folder copy of functions.php to your local computer and edit it with your text editor. Change the functions.php file name to your new file name, then save your file.
<?php
include('/home3/usr/secureconfig/keep-out.php');
?>
Step 3: Upload functions.php back to the theme directory
You’ll be asked if you want to overwrite the existing file. Click Ok.
Now WordPress should point to your renamed functions file.
Additional layers of security for functions.php
You can add some additional protection to your website as a whole, including your functions.php file, by making similar changes to your wp-config file like renaming it, hosting it outside the root directory, and denying public access.
If you see suspicious code in your functions.php files and are worried you may have been hacked already, you’ll want to read up on how to detect and remove malware from your WordPress website.
What code can I add to functions.php in WordPress?
There are a lot of different code snippets that you can add to your WordPress functions.php file. However, you’re often better served by using a plugin (or writing your own plugin) for many functions. If the code you want to add is specific to your theme, then you can add that PHP code to your child theme’s functions.php file.
Below are a handful of useful functions you might insert into your child theme’s functions.php file:
Adding a new admin user in functions.php
If you’ve lost admin access to your WordPress dashboard and can’t recover your username or password via email, you can create a new admin user through your hosting account. Either via SFTP or cPanel, you can download your functions.php file and add the following code to create a new admin user for your site.
function qode_add_new_admin_account() {
$user = 'your-username';
$password = 'your-password';
$email = 'your-email';
if ( ! username_exists( $user ) && ! email_exists( $email ) ) {
$user_id = wp_create_user( $user, $password, $email );
$user = new WP_User( $user_id );
$user->set_role( 'administrator' );
}
}
add_action( 'init', 'qode_add_new_admin_account' );
In the above code, replace ‘your-username’, ‘your-password’, and ‘your-email’ with your own credentials. Save your functions.php file and re-upload it to your theme folder. This will create a new admin user with the username, password, and email address that you’ve assigned in the code.
After you’ve uploaded your file, navigate to your site’s login page and use your new username and password to log in. Once your login is successful and you’ve confirmed that you have admin privileges, you should remove the code that you added to create your new admin account from functions.php.
Adding and removing image sizes in functions.php
When you upload an image to the WordPress Media Library, multiple variations of your image are generated. WordPress has default thumbnail, small, medium, and large sizes that are used in addition to your full size image. Your theme will generally pull the optimal image size for individual parts of your site.
If you’re creating your own theme or need to make modifications to a child theme to accommodate additional custom image sizes, you can do so in your functions.php file.
Use the following code and change your custom image size name from ‘custom-small-square’ and ‘custom-landscape’ to whatever name you’d like to use. The numbers next to your custom image size name represent the image size in pixels, so enter the pixel values with width first and height second.
function register_custom_image_sizes() {
if ( ! current_theme_supports( 'post-thumbnails' ) ) {
add_theme_support( 'post-thumbnails' );
}
add_image_size( 'custom-small-square', 450, 450, true );
add_image_size( 'custom-landscape', 1000, 600 );
}
add_action( 'after_setup_theme', 'register_custom_image_sizes' );
Keep in mind that additional custom image sizes can weigh down your site and impact load times. If you have some WordPress default image sizes that your theme doesn’t use, you may want to delete and disable those to make room for your custom sizes.
If you want to disable WordPress default image sizes, you can place this code snippet into your functions.php file:
add_filter( 'intermediate_image_sizes_advanced', 'prefix_remove_default_images' );
// This will remove the small, medium, and large default image sizes.
function prefix_remove_default_images( $sizes ) {
unset( $sizes['small']); // 150px
unset( $sizes['medium']); // 300px
unset( $sizes['large']); // 1024px
return $sizes;
}
If you only need to disable one or two sizes, you can only add those sizes to the code above and delete the code that you don’t need.
Use functions.php to allow additional file types in uploads
WordPress only allows a few different file types to be uploaded in your WordPress dashboard. This is a reasonable security measure, but you might encounter a situation where you need to upload a file type that’s not natively allowed.
To add more allowed file types to WordPress, add the following code to your child theme’s functions.php:
function additional_upload_file_types($mime_types){
$mime_types['stl''] = 'application/sla';
$mime_types['stl'] = 'application/vnd.ms-pki.stl';
$mime_types['stl'] = 'application/x-navistyle';
return $mime_types;
}
add_filter('upload_mimes', 'additional_upload_file_types', 1, 1);
For the above example, we used the stl file type, which is a CAD file type. It’s an unusual file type to upload to a website outside of certain niche industries, but if your site is for an industrial designer, engineering firm, or even an orthodontics lab, you might find the ability to upload STL files really useful.
You can replace the $mime_type variable with whatever file extension suits the needs of your website. You’ll also need to include the media type and subtype after that (e.g. ‘application/sla’ or ‘image/octet-stream’). Here’s a complete list of mime types that you can refer to.
Frequently asked questions about editing the functions.php file in WordPress
We’ve covered what the functions.php file is, how to find functions.php, how to access it, how to edit it, and a few code snippets you can add to your functions.php file. We’ll wrap things up with a few helpful answers to frequently asked questions.
Do I really need to use a child theme to edit functions.php?
The short answer? Yes.
If you’re a theme developer, you’ll definitely want to add your theme-specific functions directly to your theme’s functions.php file. If you’re modifying a theme from another developer that will get regular updates, however, you’ll absolutely want to use functions.php within a child theme.
Most theme developers will periodically make updates to their themes for security and performance reasons, or to add new features. If you change the parent theme’s functions.php file, those changes will all be overwritten when you update to your theme’s latest version. All your hard work and customizations — poof! Gone.
Child themes aren’t touched when the parent theme updates, so if you make changes to your child theme’s functions.php file, your changes will be preserved any time you update your parent theme.
I edited functions.php and now I don’t have access to my WordPress dashboard. Help!
In the unfortunate event that you edited the functions.php file and caused a critical error on your site that kept you from accessing the WordPress dashboard, don’t worry — all is not lost!
There are a few things you can do to restore access to your site. You can edit functions.php via SFTP and a text editor or directly in cPanel if you know which bit of code caused the issue. Alternatively, you can restore functions.php from a backup or download a fresh copy of functions.php from your theme developer.
I know what code I messed up. I just need to access and edit functions.php to fix it.
See How to edit functions.php above for instructions on how to access and edit your theme or child theme’s functions.php file.
I have no clue what I did to my functions.php file, but I have a backup.
If you have a backup on hand, you can access your files either on your web host’s server or your remote server (depending on where you have opted to store these files), and use them to replace your corrupt functions.php file via SFTP or cPanel.
If you feel more comfortable restoring your entire site backup rather than trying to restore just the functions.php file, our article, “How to Restore WordPress from a Backup” goes in depth on the different methods you can use to restore your WordPress site.
I have no idea what code caused the problem and I didn’t make a backup.
If you don’t have a backup, you can download a fresh copy of the theme you’re using from your theme developer, extract the functions.php file, and overwrite the broken functions.php file on your server via SFTP or cPanel.
Note: If you’re using a theme that hasn’t been updated in awhile, you may encounter issues in overwriting functions.php with a version that’s from a much more recent update. If you encounter issues, you might be better off just manually updating your entire theme to the latest version. Alternatively, you can contact your theme developer to get the theme files for your current version and use that version of functions.php.
Can I add JavaScript to my functions.php file?
Yes, you can add code to your functions.php file that will add your custom JavaScript to either specific pages, posts, or all pages and posts on your site. This article on adding JavaScript to WordPress covers all the different ways you can add JS to your functions.php file.
This entry was posted in Learn. Bookmark the permalink.
Rob Pugh
Rob is the Marketing Lead for Jetpack. He has worked in marketing and product development for more than 15 years, primarily at Automattic, Mailchimp, and UPS. Since receiving a Master of Science in Marketing Degree from Johns Hopkins University, he’s focused on delivering products that delight people and solve real problems.
Explore the benefits of Jetpack
Learn how Jetpack can help you protect, speed up, and grow your WordPress site.
Get up to 51% off your first year.
Compare plans
One of the best parts about WordPress is how customizable it can be. Its open-source nature gives you a whole world of possibilities to explore. However, knowing how to do so correctly while maintaining your site’s integrity can be tricky – especially when it comes to the functions.php WordPress file.
Fortunately, it’s not as complicated as it sounds. By familiarizing yourself with the functions.php
file, including when and how to use it, you can create a website tailored to your exact needs.
In this article, we’ll explore the purpose of the functions.php
file and some things to know before you make any changes to it. We’ll also take you step-by-step through how to find it and add your alterations. Let’s get into it!
The Purpose of the functions.php File
The functions.php
file comes with every WordPress themeA WordPress theme is a set of files that determine the design and layout of a website. It controls everything … More. It’s a template that automatically loads once a theme has been downloaded and activated. For reference, here’s a sample of what the unaltered WordPress Twenty Twenty theme’s functions.php
file looks like:
The code, written in the Hypertext Preprocessor (PHP) programming language, is critical to the functioning of your theme. The functions.php
file can add or change features on your site depending on what the theme’s developer has included.
You can also access your theme’s functions.php
file and modify it yourself to customize your WordPress site. You’re free to add, delete, or change any code you want.
The Difference Between the Core Functions File and the Theme Functions File
Themes aren’t the only place you’ll find a functions.php
file. There’s also one in your site’s root directory. This is your core functions file.
While your core functions file may seem similar to the ones you find in themes, it’s imperative that you do not edit it. It contains information that’s vital to the running of your WordPress site. A mistake in this file could break your whole site.
Fortunately, this scenario is fairly easy to avoid. Whenever you’re about to edit a functions.php
file, double-check that it’s located within a theme. This will lower the chances of making changes to the wrong part of your site.
Why You Might Need to Edit functions.php
When used correctly, functions.php
can be an effective way to customize the look and feel of your site. For example, you can use it to create custom navigation menusIn WordPress, a menu is a collection of links that are displayed as a navigation menu on a website. Menus are … More, add new editor styles, and provide unique error messages.
You can also make more practical adjustments with the functions.php
file. If you’re looking to add Google Analytics to your site, you can do so here. Editing it can also help you increase your site’s maximum upload size.
There are some changes you just can’t make through the WordPress Customizer alone. Whether you’re looking to implement a new aesthetic or make practical changes to your theme, a little familiarity with the functions.php
file can go a long way.
Where to Find functions.php in WordPress (2 Key Locations)
If you’re interested in accessing your theme’s functions.php
file, you can easily find it in two locations. Which one you should seek out depends on whether you’re editing an active or inactive theme, the scale of the changes you plan to make, and your personal preferences.
1. The themes Directory
The first place you can find your theme’s functions.php
file is in your site’s themes
directory. If you’re trying to access the file for an inactive theme, you’ll need to use this method. However, it can also be used for active themes.
This method requires the use of a File Transfer Protocol (FTP) client such as FileZilla. Open your FTP client of choice and navigate to your root directory (usually public_html
):
Continue on to wp-content/themes/
and locate the folder for the theme you’d like to edit. In this example, we’ll go to wp-content/themes/twentytwenty/
:
Once you’ve accessed the folder for the theme you want to change, you’ll find the functions.php
file within it. Right-click on it to open it with your editor of choice and start making alterations.
This method is recommended if you’re planning to make extensive changes to your site’s theme. By editing functions.php
using a third-party platform, you can work on it gradually and reupload it via FTP when you’re ready to apply your customizations.
2. The WordPress Theme Editor
If you’re making quick changes to an active theme and don’t want to use an FTP client, you can use the built-in WordPress theme editor to access functions.php
. Start at your WordPress dashboardIn WordPress, the Dashboard is a central hub for managing a website’s content and settings. It is the first sc… More and navigate to Appearance > Theme Editor
.
From the right-hand menu, select Theme Functions
. This will bring up your theme’s functions.php
file in a screen that looks similar to this:
From here, you can make alterations to the file as necessary. Just remember to click on Update File
to save your changes when you’re done.
Key Considerations to Keep In Mind When Editing functions.php
Whenever you need to edit your theme’s functions.php
file, you should consider using a child themeA child theme is a WordPress theme that inherits the functionality and styling of another theme, referred to a… More. A child theme operates identically to its parent theme while letting you customize it in a controlled environment. This protects the original theme from any mistakes you might make.
Additionally, customizing a child theme prevents theme updates from overriding your changes. Developer updates will apply to the parent theme and be inherited by the child theme, but your child theme’s files won’t be affected.
You can create a child theme manually by adding the required folders and files to your site’s themes
directory, or use a pluginA plugin is a software component that adds specific features and functionality to your WordPress website. Esse… More such as Child Theme Configurator:
Even when using a child theme, there are some disadvantages to directly editing a functions.php
file. One example is that any changes you make will only apply to the theme that the edited file belongs to. If you need to switch themes for some reason, your customizations won’t be carried over.
Furthermore, the functions.php
file can become disorganized if you’re making several changes. Edits over time can become jumbled and messy. This can make undoing any of your additions a challenge.
Fortunately, the Code Snippets plugin provides an alternative to editing functions.php
directly:
Code Snippets can come in handy in a lot of situations. For example, you might not be comfortable editing code. This plugin can help you manage your changes without having to access the functions.php
file yourself.
This plugin can also help you keep multiple edits organized. This can make it easier to go back and review any changes. It’s also a powerful tool if you’re looking to apply a change to multiple themes without having to access each individual functions.php
file.
Conclusion
Given its proximity to the rest of your site’s code, knowing exactly how to get to your WordPress theme’s functions.php
file and change it successfully can be tricky. Fortunately, armed with a little bit of knowledge, you’ll be using it like a pro in no time.
In this article, we covered two ways to find and change your functions.php
file:
- Use an FTP client to access your
themes
directory. - Access the native theme editor within WordPress.
Do you have any questions about using the functions.php
file? Let us know in the commentsComments are a feature of WordPress that allow users to engage in discussions about the content of a website. … More section below!