Хорошо. Предположим, что дистрибутив вашего WordPress’а лежит на локальной машине, в директории
C:WordPress 3.9.1 RU
тогда все файлы header.php находятся по следующим адресам:
C:WordPress 3.9.1 RUwp-adminadmin-header.php
C:WordPress 3.9.1 RUwp-admincustom-header.php
C:WordPress 3.9.1 RUwp-contentthemestwentyfourteeninccustom-header.php
C:WordPress 3.9.1 RUwp-contentthemestwentythirteeninccustom-header.php
C:WordPress 3.9.1 RUwp-contentthemestwentytwelveinccustom-header.php
C:WordPress 3.9.1 RUwp-contentthemestwentyfourteenheader.php
C:WordPress 3.9.1 RUwp-contentthemestwentythirteenheader.php
C:WordPress 3.9.1 RUwp-contentthemestwentytwelveheader.php
C:WordPress 3.9.1 RUwp-includestheme-compatheader.php
C:WordPress 3.9.1 RUwp-adminmenu-header.php
C:WordPress 3.9.1 RUwp-blog-header.php
Выбирайте тот, который вам нужен.
Если мы говорим об удалённом сервере, то путь к искомым файлам будет следующий (корневой директорий может быть отличный от www, например public_html):
ftp://ВАШ_САЙТ.РУ/www/wp-admin/admin-header.php
ftp://ВАШ_САЙТ.РУ/www/wp-admin/custom-header.php
ftp://ВАШ_САЙТ.РУ/www/wp-content/themes/twentyfourteen/inc/custom-header.php
ftp://ВАШ_САЙТ.РУ/www/wp-content/themes/twentythirteen/inc/custom-header.php
ftp://ВАШ_САЙТ.РУ/www/wp-content/themes/twentytwelve/inc/custom-header.php
ftp://ВАШ_САЙТ.РУ/www/wp-content/themes/twentyfourteen/header.php
ftp://ВАШ_САЙТ.РУ/www/wp-content/themes/twentythirteen/header.php
ftp://ВАШ_САЙТ.РУ/www/wp-content/themes/twentytwelve/header.php
ftp://ВАШ_САЙТ.РУ/www/wp-includes/theme-compat/header.php
ftp://ВАШ_САЙТ.РУ/www/wp-admin/menu-header.php
ftp://ВАШ_САЙТ.РУ/www/wp-blog-header.php
Один из ключевых файлов темы WordPress, который отвечает за подключение стилей, встроенных функций и скриптов. Благодаря ему происходит передача всех необходимых данных для поочередного запуска модулей и структуры сайта браузеру. Не требует постоянной настройки.
Что такое хедер сайта?
Прямой перевод – «шапка». Находится в верхней части, может быть оформлена по общему стилю или индивидуально. Основные элементы:
- название;
- слоган;
- логотип компании;
- контактные данные;
- навигация
Используя правильную компоновку навигационных элементов, привлекательный дизайн и краткую информацию о деятельности сайта, можно значительно улучшить поведенческие факторы, включая первое впечатление посетителей. Header.php находится в корневой директории выбранного шаблона.
Для улучшения работы сайта – “Как правильно обновить и подключить jQuery в ВордПресс”
Содержимое header WordPress
Добавление метатегов в хедер осуществляется при помощи текстового редактора (рекомендуется Notepad++). В их список входят: head, title, meta, script, link. Как пример, рассмотрим наиболее полный файл без лишних элементов. Дальнейшее внедрение дополнительного функционала зависит от потребностей отдельного заказчика.
Редакция сайта рекомендует – “Как добавить функции WordPress в пользовательский файл PHP”
Кодовая часть
Необходимо добавить следующие строки в верхнюю часть functions.php:
define(“THEME_DIR”, get_template_directory_uri()); /*— REMOVE GENERATOR META TAG —*/ remove_action(‘wp_head’, ‘wp_generator’); // ENQUEUE STYLES function enqueue_styles() { /** REGISTER css/screen.css **/ wp_register_style( ‘screen-style’, THEME_DIR . ‘/css_path/screen.css’, array(), ‘1’, ‘all’ ); wp_enqueue_style( ‘screen-style’ ); /** REGISTER HTML5 Shim **/ wp_register_script (‘html5-shim’, ‘http://html5shim.googlecode.com/svn/trunk/html5.js’, array(‘jquery’ ), ‘1’, false ); wp_enqueue_script( ‘html5-shim’ ); /** REGISTER HTML5 OtherScript.js **/ wp_register_script( ‘custom-script’, THEME_DIR . ‘/js_path/customscript.js’, array( ‘jquery’ ), ‘1’, false ); wp_enqueue_script( ‘custom-script’ ); |
В header.php следует прописать код:
<!doctype html> <html <?php language_attributes(); ?> class=”no-js no-svg”> <head> <!–=== META TAGS ===–> <meta http-equiv=”X-UA-Compatible” content=”IE=edge,chrome=1″> <meta charset=”<?php bloginfo( ‘charset’ ); ?>” /> <meta name=”description” content=”description”> <meta name=”keywords” content=”keywords”> <meta name=”author” content=”Your Name”> <meta name=”viewport” content=”width=device-width, initial-scale=1, maximum-scale=1″> <!–=== LINK TAGS ===–> <link rel=”shortcut icon” href=”<?php echo THEME_DIR; ?>/path/favicon.ico” /> <link rel=”alternate” type=”application/rss+xml” title=”<?php bloginfo(‘name’); ?> RSS2 Feed” href=”<?php bloginfo(‘rss2_url’); ?>” /> <link rel=”pingback” href=”<?php bloginfo(‘pingback_url’); ?>” /> <!–=== TITLE ===–> <title><?php wp_title(); ?> – <?php bloginfo( ‘name’ ); ?></title> <!–=== WP_HEAD() ===–> <?php wp_head(); ?> |
Подробно рассмотрев пример, указанный выше, разделим его на несколько важных элементов, обязательных в файле:
- doctype; (Тип документа)
- языковые атрибуты (ранее использовались условия для браузеров старых версий, однако современный вариант упускает этот момент);
- список метатегов;
- фавикон, RSS, пингбек;
- заголовок;
- при необходимости функции «wp_enqueue_script» и «wp_enqueue_style».
Важно: В сети можно встретить рекомендации добавлять комментарии к строкам, ведь – это сократит время поиска нужных кодов. На самом деле, с точки зрения поисковой эффективности – это мусор на который можно сократить страницу. Мы рекомендуем не злоупотреблять комментариями и прибегать к ним в крайних случаях.
Рекомендуем к прочтению –“Актуальность скриптов WordPress в 2020 году”
Работа с function.php
Указанный ранее код уже помещен в функциональный файл. Некоторые элементы позволяют нам сократить затраты ресурсов сервера на обработку запросов путем создания константы THEME_DIR. Это изложено в первой строке, где сохраняется директория шаблона. Является важным элементом оптимизации темы. Некоторые вебмастера идут сложным путем, вызывая повторные запросы через «get_template_directory_uri()».
Следующая строка избавляет от генератора метатегов, который демонстрирует текущую версию шаблона пользователям (включая злоумышленников).
/*— REMOVE GENERATOR META TAG —*/; remove_action(‘wp_head’, ‘wp_generator’); |
Добавление CSS
Теперь необходимо добавить тег link в header.php – для этого создается функция:
// ENQUEUE STYLES; function enqueue_styles() { /** REGISTER css/screen.cs **/ wp_register_style( ‘screen-style’, THEME_DIR . ‘/css_path/screen.css’, array(), ‘1’, ‘all’ ); wp_enqueue_style( ‘screen-style’ ); |
Используются «wp_enqueue_script» и «wp_enqueue_style» согласно рекомендациям руководства по WordPress. Очередность действий:
- Создание «enqueue_styles».
- Вызов «add_action», если происходит событие «wp_enqueue_scripts».
Содержит внутри строки:
/** REGISTER css/screen.cs **/; wp_register_style( ‘screen-style’, THEME_DIR . ‘/css_path/screen.css’, array(), ‘1’, ‘all’ ); wp_enqueue_style( ‘screen-style’ ); |
Для регистрации таблицы стилей используется «wp_register_style», она требует список параметров:
- Выбор доступного имени.
- Указание пути к файлу (в данной ситуации используется константа THEME_DIR).
- Вписываются условия, необходимые файлы для предварительной загрузки, название стилей.
- используемая версия.
- Медиа-атрибут тега link.
Далее, вызывается «wp_enqueue_style» и передается имя стиля, который будет применен. Для добавления нескольких образцов в header WordPress можно повторно копировать строки, а также изменять имеющиеся параметры.
Советуем к прочтению – “Как добавить страницу администратора, не добавляя ее в меню”
Добавление скриптов
Применяя данный код происходит добавление скриптов:
// ENQUEUE SCRIPTS; function enqueue_scripts() { /** REGISTER HTML5 Shim **/ wp_register_script (‘html5-shim’, ‘http://html5shim.googlecode.com/svn/trunk/html5.js’, array(‘jquery’ ), ‘1’, false ); wp_enqueue_script( ‘html5-shim’ ); wp_register_script( ‘custom-script’, THEME_DIR . ‘/js_path/customscript.js’, array( ‘jquery’ ), ‘1’, false ); wp_enqueue_script( ‘custom-script’ ); |
Процесс аналогичен подключению стилей, но используются другие функции («wp_register_script» и «wp_enqueue_script»). Для первой необходимы схожие параметры, как для «wp_register_style» – отличается лишь 5 пункт, в котором определяется, будет ли добавлен вызов через «wp_head» (значение fals) или «wp_footer» (значение true).
Через «wp_enqueue_script» указывается имя скрипта для интеграции. Для большего количества образцов необходимо повторно скопировать код, изменить параметры, имя и директорию.
Header WordPress
Стандартный файл содержит набор тегов и функций, используемых по умолчанию. Рассмотрим их особенности и функционал.
<html>
Устанавливаются языковые атрибуты или добавляются классы в соответствии с версией браузера (больше не применяется).
<html <?php language_attributes(); ?> class=”no-js no-svg”> |
Добавление метатегов в хедер является важной операцией, поскольку браузеру передается важная информация для правильного отображения темы.
Строка отключающая использование браузером Quirks Mode – данный режим плохо сказывается на разметке:
<meta http-equiv=”X-UA-Compatible” content=”IE=edge,chrome=1″> |
Указание кодировки для правильного отображения шрифтов:
<meta charset=”<?php bloginfo( ‘charset’ ); ?>” /> |
Параметры, улучшающие SEO-показатели ресурса (описание, ключевые слова):
<meta name=”description” content=”description”>
<meta name=”keywords” content=”keywords”> |
<link>
Добавление favicon для сайта:
<link rel=”shortcut icon” href=”<?php echo THEME_DIR; ?>/path/favicon.ico” /> |
Ссылка RSS-ленты:
<link rel=”alternate” type=”application/rss+xml” title=”<?php bloginfo(‘name’); ?> RSS2 Feed” href=”<?php bloginfo(‘rss2_url’); ?>” /> |
Ссылка пингбек:
<link rel=”pingback” href=”<?php bloginfo(‘pingback_url’); ?>” /> |
<title>
Высокая важность. Изменяет стандартный заголовок, улучшая SEO-параметры:
<title><?php wp_title(); ?> – <?php bloginfo( ‘name’ ); ?></title> |
Список стандартных и наиболее применяемых функций:
- wp_head WordPress – используется для добавления кода из плагинов, скриптов, библиотек;
- get_header WordPress – выполняет подключение файла шаблона (для каждой страницы отдельное имя).
Заключение
Таким образом осуществляется настройка header WordPress. Файл требует вмешательства только на начальном этапе подготовки темы. Повторное использование необходимо при подключении дополнительных функций, скриптов или таблиц стилей. Рассмотрены основные теги и их предназначение. Разработчики постоянно модернизируют платформу для минимизации человеческих действий в редактировании подобных файлов. Для безопасности, не рекомендуется использовать сторонние и непроверенные скрипты.
Для расширения ваших знаний – “Настройка файла robots.txt для WordPress”
WordPress is the world’s most popular Content Management System (CMS). Because it’s an open source platform, you can easily make your own edits to your installation of WordPress. This level of flexibility is one of the main benefits of the CMS. But nearly every WordPress site requires some tweaking to be successful. Say you want to integrate Google Analytics or a comparable tracking script, for example. Then you’ll need to add snippets of code to your theme’s framework. These kinds of administrative tasks often involve editing the WordPress header. We’ll show you the best ways to do this in our step-by-step guide.
Contents
- What is a WordPress header and what are its elements?
- Invisible elements in the HTML head
- Visible elements in the page header
- How to edit a header in WordPress?
- Use a plugin to edit WordPress header
- Modify the theme code to edit the WordPress header
- Add code in the header.php file
- and closing tag. In addition to a few meta tags, the HTML head contains a call to the WordPress function wp_head – a so-called WordPress hook. Programmatically, this is linked so that other elements can be placed in the HTML head. These elements are added before the closing
- Create functions in functions.php
- Adding additional scripts and stylesheets in WordPress — here’s how to do it
- Create a child theme
- Using the Google Tag Manager to edit a WordPress header
What is a WordPress header and what are its elements?
The term “WordPress header” can be confusing. In connection with a website, the header usually describes the visible area at the top of a page. That’s usually where you find the site logo and the main page menu. Almost every website has a header. On the other hand, a HTML document, colloquially referred to as a “page”, comprises two components: the HTML head (<head>) and the HTML body (<body>). Visible elements are only contained in the HTML body, while invisible elements appear only in the HTML head.
WordPress Managed Hosting with IONOS!
Start your website quickly and benefit from the most secure and up-to-date version of WordPress!
Tip
Publish your own WordPress site with IONOS. Get professional WordPress Hosting now.
In WordPress, the header includes both the HTML head and the header of the page. So, when we talk about changing the WordPress header, we are refering to two types of elements:
- Invisible elements in the HTML head
- Visible elements in the page header
We’ll explain both elements in the following sections.
Invisible elements in the HTML head
Elements in the HTML head are not visible to page visitors. Instead, they’re evaluated by a browser and search engines. The most common elements found in an HTML head include:
- Links to stylesheets
- Links to script files
- Links to fonts
- Links to favicons
- Various types of meta tags
Note
Script tags placed in the HTML head may hamper performance, e.g., slow down page loading. Depending on the application, the problem can be remedied by adding the “async” and “defer” attributes. It’s advisable to include such script tags in the WordPress footer.
Visible elements in the page header
The page header contains visible elements at the top of the page. As of HTML5, it’s been customary to implement the page header with a <header> element. However, this is not mandatory. In principle, a <div> element can be used as well. The following elements are often found in a page header:
- Logo
- Menu
- Header image
- Search bar
How to edit a header in WordPress?
As briefly mentioned, when editing a header in WordPress we need to distinguish between adding additional code to the HTML head or changing the visual appearance of the site. In the following, we focus on the integration of additional non-visual elements in the HTML head.
Visual changes to the page header are much more complex. How exactly you do this depends on the theme you used. Furthermore, these changes usually require some design and coding skills.
Note
Some added script tags may require user consent before they can be loaded. That’s the case if, for example, cookies are used or personal data is collected. You will then need to consider how each additional script is integrated into an existing cookie-consent solution.
Here are three methods to place additional code in the HTML head of the WordPress header:
- Use a plugin
- Modify the theme code
- Use the Google Tag Manager
The advantages and disadvantages of each method are summarized below:
Method | Advantage | Disadvantage |
---|---|---|
Use a plugin | Simple application | Code snippets are stored in the database; difficult to integrate with cookie consent; lack of control; can cause performance problems |
Modify the theme code | Code snippets become part of the codebase; visual changes possible; full control over complex applications | Requires editing of theme code and coding skills |
Use the Google Tag Manager | Simple application; code snippets are managed centrally outside of the website; integrates well with cookie consent; In principle, it is also possible to implement complex applications | Requires one-time set-up |
Use a plugin to edit WordPress header
You can access various plugins to help insert code in the HTML head from the WordPress Plugin Directory. These plugins are primarily suitable to add meta tags, stylesheets, or scripts to a page. Adding visible elements to the page header is usually not possible. The plugins are easy to use and most can be added without prior coding skills. Depending on the plugin, control over the inserted code is limited. Here is an overview of widely used header code plugins:
- Head, Footer and Post Injections
- Header and Footer Scripts
- Header Footer Code Manager
Below, we’ll show you how to use the “Header and Footer Scripts” plugin to place additional code in the HTML head of the WordPress header step-by-step.
Modify the theme code to edit the WordPress header
By modifying the theme code, you retain full control over the content of your WordPress header. Any changes made become part of the theme codebase and are therefore subject to version control. This is the preferred option for experienced users and admins. You have several options to modify the theme code:
- Add code to the template file header.php
- Add additional functions in the functions.php file
- Create a child theme and add changes
Method | Advantages | Disadvantages |
---|---|---|
Add code to header.php | conceptually simple to grasp; precise control of the order of code injections; also works for visible changes | hardcoded changes; with repeated changes there is a greater risk of them becoming confusing |
Create functions in functions.php | clear separation between presentation and functionality; the order in which the code is injected can be specified | greater complexity; can be confusing for beginners |
Create child theme | changes are update-safe and can be easily undone if necessary | slightly higher effort; requires a one-off modification to the theme |
Add code in the header.php file
The most straightforward way to add code to the WordPress header is to edit the “header.php” file. This WordPress file is a universal template that is used across nearly every theme. Let’s exemplify this by looking at the official “TwentyTwenty” theme to see how a typical header.php file is structured:
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1.0" >
<link rel="profile" href="https://gmpg.org/xfn/11">
<?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
<?php
wp_body_open();
?>
<header id="site-header" class="header-footer-group" role="banner">
The code above shows the WordPress header. The HTML head sits between the opening <head> and closing </head> tag. In addition to a few meta tags, the HTML head contains a call to the WordPress function wp_head – a so-called WordPress hook. Programmatically, this is linked so that other elements can be placed in the HTML head. These elements are added before the closing </head> tag. The wp_head hook is therefore only suitable for adding non-visible elements.
To add more elements to the HTML head, simply place your code before or after the wp_head () call. Please note that the order of the elements is important, especially when it comes to stylesheets and scripts. With meta tags the order usually doesn’t matter. Stylesheet and script tags should not be manually placed in the WordPress header. You can find out more about this in the following section.
The HTML head is followed by the HTML body whereby the opening <body> tag is followed by a header element
Create functions in functions.php
Much like the header.php file, the functions.php is found in most WordPress themes. However, it’s not a PHP template that is translated directly into HTML. Rather, the code in functions.php is used to configure the theme and the site. It is possible to define functions and link them to the WordPress hooks. As a simple example, let’s add a robots meta tag in the HTML head:
function robots_meta() {
echo '<meta name="robots" content="index, follow, noarchive">';
}
add_action( 'wp_head', 'robots_meta' );
First, we define a new function in functions.php, which outputs the HTML code of the meta tag. We call this robots_meta (). You can choose any name, but it’s best to select one that reflects what the function does. The WordPress function add_action () is named after the function definition. We name this WordPress hook “wp_head”, which we’ll use to link to our function called “robots_meta”. A call to wp_head () then leads to a call to robots_meta (); the HTML code contained in robots_meta () is output in the HTML head.
Let’s modify our example. We want to enable the inclusion of the “is_front_page ()” into the Google cache by omitting “noarchive” on the WordPress homepage. And we want to exclude pages where WordPress comments are activated (“is_single () && comments_open ()”) from being indexed by adding “noindex”:
function robots_meta() {
if ( is_front_page() ) {
echo '<meta name="robots" content="index, follow">';
}
else if ( is_single() && comments_open() ) {
echo '<meta name="robots" content="noindex, follow, nocache">';
}
else {
echo '<meta name="robots" content="index, follow, nocache">';
}
}
add_action( 'wp_head', 'robots_meta' );
Adding additional scripts and stylesheets in WordPress — here’s how to do it
Sometimes you need to add external software such as a tracking script or a cookie consent solution to a WordPress site. Often, it’s recommended to paste a code snippet directly into the WordPress header to load additional scripts or stylesheets. In practice, this requires a certain amount of caution, because the order in which scripts or stylesheets are added is critical!
Newly defined style properties complement or overwrite previously defined properties. If the order of the style definitions is reversed, it can lead to serious display errors. The same goes for scripts. If a script accesses variables or functions that have been defined in another script, there is a dependency. The dependent script must be loaded last.
WordPress has special functions and hooks to integrate additional scripts and stylesheets. The scripts and stylesheets are queued up (“enqueue”) and that’s reflected in their names e.g., “wp_enqueue”. The following code is an example of how stylesheets and scripts are loaded within functions.php:
function add_theme_scripts() {
wp_enqueue_style( 'main-style', get_stylesheet_uri() );
wp_enqueue_script( 'main-script', get_template_directory_uri() . '/js/main.js', array( 'jquery' ));
}
add_action( 'wp_enqueue_scripts', 'add_theme_scripts' );
Create a child theme
When you’re adapting code of a WordPress theme, it’s advisable to create a child theme. The child theme “inherits” the code of the “parent theme”, selectively adding and overwriting components. Using a child theme ensures that changes are separated from the original theme code. It also means that updates can be made without overwriting the original parent theme. The two methods previously discussed can be used to create a child theme.
Register a domain name
Build your brand on a great domain, including SSL and a personal consultant!
Private registration
24/7 support
Using the Google Tag Manager to edit a WordPress header
Aside from plugins or modifying the theme code to place code in a WordPress header, there’s one more option: using the Google Tag Manager. You’ll only need to add it once to your site, either by adding the theme code or using a plugin. From a separate interface in your Google account, you can then track code and meta tags and integrate them into your WordPress site. This is often the preferred method for marketing managers because it enables them to anchor specific code in the HTML head without requiring the help of professional coders.
Conclusion
If you’re managing extensive changes to header code on a commercial WordPress site, it’s best to use the Google Tag Manager. If you’re a developer or you partner with coders, you can create a child theme. Plugins are only recommended for making simple changes to the WordPress header.
Related articles
How to embed a Video in WordPress
Video content adds the finishing touches to your WordPress site. Now more than ever before, videos are in high demand. They’re not only eye-catching but also deliver important content. In this article, we’ll discuss the various options to embed videos in WordPress and show you how WordPress video plugins work.
How to embed a Video in WordPress
How to Change Your WordPress Username and Password
Learn how to change your WordPress username and password. With this guide we will show you how to easily change your WordPress username and/or password.
How to Change Your WordPress Username and Password
How to enable Theme- and Plugin Editor in WordPress
When you set up your WordPress installation with our Click & Buildapplications, we make some settings and add features to make creating your website easier and safer. For example, we disable the theme and plugin editors. This article explains how you can reactivate the Theme and Plugin Editor afterwards.
How to enable Theme- and Plugin Editor in WordPress
How to add JavaScript to WordPress
Scripts in JavaScript are a handy way to fill websites with interactive content. However, in order to prevent problems with malicious code from occurring, WordPress only allows administrators to add JavaScript by default. We’ll show you how to enable JavaScript for all backend users in our dedicated article. Read on for more.
How to add JavaScript to WordPress
Обратно пишу тебе разлюбезный читатель, поскольку выдалась свободная минутка. И одолела меня непреодолимая тяга, поведать о том —
Как легко изменить шапку сайта
Тем паче, обещал я это в прошлой своей статье — Как установить шаблон на WordPress.
Пардоньте, за такой вот сплагиаченный слог приветствия, из фильма «Белое солнце пустыни», не смог удержаться. Надеюсь никто не в обиде.
Сегодня, как уже всем стало понятно, речь пойдет о том, как же можно изменить стандартную шапку блога. Т.е. о том, как вставить новую картинку в верхнюю часть нашего сайта, которая называется Хедер (Header).
Для экспериментов, опять буду использовать клон своего блога, размещенный на локальном сервере.
Итак, поехали.
В первую очередь необходимо зайти в админ панель и немножко изменить код, в двух файлах, которые отвечают за отображение хедера и за стили. Файлы эти называются: header.php и style.css соответственно.
Зачем же, что-то менять? Да еще и в коде. Спросите вы. Отвечаю! Вся беда в том, что функционал шаблона GreenChilli, позволяет вставить картинку размером, всего лишь 286×50 px. Это, как вы понимаете, очень маленький размер, который не совсем соответствует идее блога.
Заходим в админку, переходим к меню «Внешний вид», следом к меню «Редактор» и наблюдаем перед глазами, окно редактора. Ищем справа файл header.php, кнопаем на него, и видим тот самый код, в который сейчас будем вносить изменения. Я выделил кусочек кода, который отвечает за саму картинку в шапке и за вывод формы поиска справа. Как видим этот код заключен между тегами
<div id=»header»> </div>
Использование атрибута id говорит о том, что стилевой идентификатор, в данном случае header, должен быть в единственном экземпляре. Это я так решил поумничать.
Внешний вид идентификатора header, т.е. нашей шапки, заключенного в теги <div> </div > прописывается в файле стилей — style.css
Код, который отвечает за вывод формы поиска, мы трогать не будем, а вот все остальное безжалостно удалим. Так же необходимо удалить скобочку вот здесь <?php }
Жмем на кнопку «Обновить файл»
Небольшой совет, дорогой читатель, перед тем вносить какие-либо изменения в код, сохраняй редактируемый файл. Сколько раз бывало уже, наудаляеш чего-нибудь, а шаблон потом раз, и перекосило.
Итак, давайте посмотрим, что у нас получилось.
Вот это белое поле вверху, и будет место для нашей новой шапки. Единственно, что мне не сильно нравится, это форма поиска с правой стороны. Удалять ее не будем, а просто спрячем.
Возвращаемся опять в редактор, выбираем файл style.css, ищем в этом файле вот такой блок.
И после открывающей скобочки вставляем следующую строчку – visibility: hidden; Нажимаем «Обновить»
В результате код должен выглядеть вот так.
Все! Место для новой шапки подготовлено. Осталось только, ее нарисовать и вставить.
Советую скачать очень удобную программку. Которая в дальнейшем, очень пригодится и которая называется PicPick. Функций у нее много, но что потребуется в данный момент, так это линейка. Качаем программку, устанавливаем.
Измеряем линейкой это белое поле и у нас получается 960 на 114 px.
Теперь необходимо подготовить красивую картинку такого точно размера, вставить там свою фотографию, нарисовать логотип, написать имя сайта, и т.д., и т.п. Я ограничился малым, тем, что сделал синий фон, написал название сайта, сделал небольшой логотипчик и придумал слоган.
Как делать картинку в Фотошопе или в другом графическом редакторе, я расскажу в позже. В принципе, ничего мега сложного в этом нет. Я думаю справится любой, у кого есть хоть какой-то, малейший опыт работы в этой программе.
Итак, картинка готова. Называем ее ну, например, header.jpg, и заливаем на хостинг по FTP. Причем заливаем по адресу ….wp-content/themes/greenchilli/images
Далее опять открываем редактор. Открываем файл стилей, ищем вот такой блок:
И после открывающей скобки вставляем вот такой вот код:
background: url (‘…/greenchilli/images/header.jpg’);
В результате должно получиться так:
Нажимаем “Обновить», переходим по адресу блога в браузере и любуемся новой симпатичной шапочкой.
Пожалуйста подписывайтесь на новые статьи. Никакого спама, только полезная информация.
Вот и все! Таким вот образом мы разобрались с тем как изменить шапку сайта нашего любимого WordPress. Если остались вопросы, пишите в комментариях, всегда буду рад помочь.
The header is one of the most important areas of any website. It’s at the top of the page and it appears on nearly every page of your site so you should customize it and use it smartly. A lot of our users had doubts about this so here’s a step-by-step guide on how to edit the header in WordPress.
Self-hosted WordPress is the best and most comfortable Content Management System (CMS) out there for creating anything you want. When you’re starting a site, all you need is to sign up for hosting, install WordPress, and write content. It’s that simple. However, if you want to unleash all the power of WordPress and make the most of it you should customize it.
One of the most simple and crucial customizations every user needs is changing the website header. In this article, we are going to show you how you can edit the header in WordPress without hiring any freelancer.
What’s the WordPress header?
In WordPress, the header is the element at the top of the web page. This element appears on every single page of the site and usually contains a logo, a menu to access different sections of the site, a search bar, and contact information. In eCommerce stores, it’s also common to see the cart and the products you’ve added to it. For example, at QuadLayers, the header is the top bar that you see on every page.
Why edit the header in WordPress?
The header is one of the most important areas on your website. It’s the first thing that visitors see when they get to your site and, as you probably know, first impressions matter. According to a recent study, users decide in 0.05 seconds if they like your website or not, and hence if they’ll stay or leave.
Additionally, research carried out by Nielsen Norman Group, showed that, on average, a visitor remains on a site for only 10-20 seconds. It doesn’t matter if your content is great. If they don’t like what they see and leave, they’ll never get to that amazing content. So, you must have an appealing header that makes users stay on your site.
The WordPress header also has important information to help users navigate your site and many calls-to-action (CTAs). So, to make the most of it, you must customize the header.
How to edit the header in WordPress – 3 Methods
There are several ways to edit the header in WordPress. Here, we have outlined 3 beginner-friendly ways that you can follow:
- Using a plugin
- Editing the theme’s header.php file
- With an FTP client
Let’s have a closer look at each of them.
1) Customize the Header using a plugin
If you prefer WordPress plugins over coding and modifying the core files, this is the best option. In the WordPress plugins repository, there’s a free plugin available called “Insert Headers and Footers“. This simple tool doesn’t need any additional complex configurations. So, let’s see step-by-step how you can edit the header using Insert Headers and Footers plugin.
- First, log in to your WordPress backend.
Go to Plugins > Add New. From there, you can install new WordPress plugins by searching the repository or by uploading the plugin files. In the search bar, type Insert Headers and Footers.
3. Select the correct option and install it. Then, activate it.
4. Now, we are ready to configure it. Under the Settings section, you’ll see the Insert Headers and Footers Settings as shown below.
There, you’ll see that you can edit three sections:
- Header
- Body
- Footer
If you add a code in the header section, it will be visible before the </head> tag. The same goes for the body and the footer. Codes will appear before the </body> and </footer> tags respectively. In this case, you are editing the header, so look for the </head> tag. 5. In Scripts in the Header section, add the code you want to go under the head tag.
6. Once you have added the code, don’t forget to save the changes by clicking Save.
7. That’s it! The code will be added to your header. All in all, using Insert Headers and Footers is super simple so it’s an excellent choice for those who want to edit their WordPress header without any hassle or coding.
2) Change the theme’s Header.php file
If you want to have more control over your header and have some basic coding skills, there are other options. If you’re not a fan of using too many plugins to avoid slowing down your website or you simply don’t want to use the Insert Headers and Footers plugin, don’t worry. Here we’ll show you how you can still edit your WordPress header with a bit of coding step-by-step.
To do this, you’ll need to modify the theme’s core files. So, before you start, we recommend you create a child theme. You can create one manually or using a child theme plugin. Once you’ve created the child theme, let’s see how you can modify the header file using the WordPress admin dashboard.
- First, log in to the admin section.
2. Under the Appearance section, you’ll see the Theme Editor.
3. Here you can make changes to the theme’s core files. By default, the editor will pull the current theme’s style.css file to edit and it’ll look something like this.
4. On the right side, you will see all the files and folders available in your current theme’s directory.
5. Scroll down the list until you find the header.php (under the Theme Header).
6. Select the file, and it will open in your editor. To create this guide, we’re using the GeneratePress WordPress theme so it looks like this.
7. Now, the fun begins. While editing the header.php file and adding your custom code, make sure that you add the snippet between the <head> and </head> tags. In this case, we are going to add a sample text right before the </head> tag.
8. Click Update File to save the changes. If you see the File edited successfully message, the changes are saved correctly. You can verify it by going to your site’s frontend and viewing the source.
That’s it! That’s how you edit the header in WordPress via the header.php file. It can also be useful to add some other customizations to the header. Let’s have a look at some of them.
Add Tracking codes
If you want to add a Google Analytics tracking code, Google AdSense auto ads code/ verification code, Facebook Pixel, or even Google search console verification code, you should place it right before the </head> tag. If you do this, make sure that you have updated the file after adding the snippets, otherwise, it won’t work.
PRO TIP: Change the Font Size and Style of WordPress Header
In some cases, apart from editing the text, you may want to change the font or style of the WordPress header. Let’s have a look at how you can do it. To change the style of your header, you need to know a bit of CSS. However, here we are going to show you how you can edit the font size in a very simple way.
- To add a bit of CSS code to your blog, you have to go to the Appearance section, and click Customize.
2. There, you’ll find several configuration options. You can configure your entire website according to your installed theme’s configuration and some premium themes like Divi or GeneratePress also allow you to have custom configurations in the customizer.
3. Even though these configurations might be different depending on your WordPress theme, you’ll be able to understand how to do it with one example. In our case, we are using the GeneratePress Lite WordPress theme so we click Additional CSS.
4. Here, you can edit the CSS code of your existing theme to customize your header. First, check the page source to find the right CSS class. In our case, it’s the main-title so that’s what we should edit.
For example, let’s say that you need to change the font style of your header and make it italic. Simply add:
.main-title { font-style: italic; }
And that’s it. You’ve changed the font style of your WordPress header. Additionally, you can assign custom CSS to change other things such as:
- Font-family: font: Arial – This will change the font to “Arial”
- Size: font-size: 16px – This will change the font size to 16 pixels so if you want to set a size of 24 for example, simply write 24 instead of 16 in the code.
3) Edit Header Via FTP
This is also an easy way for beginners. If you have issues with the WordPress theme editor, you could use an FTP client. For this tutorial, we are using FileZilla because it’s our favorite but if you like a different one, any will do. Now, let’s see how to edit the WordPress header via FTP.
- To connect FTP to your server, you need an FTP account. From the hosting cPanel, you can create one. Then, with the username, hostname, password port, connect the FTP client with your server.
2. On the left side, you will see the local storage, and on the right side, the server storage. To edit the header file, go to your active theme’s directory.
3. The path will be /wp-content/themes/theme-name/. There, you will see the header.php file.
4. Right-click on it and choose the editing option. The file will be saved to your local storage and it will be opened with a file editor like Notepad or Notepad++.
5. Here make the changes you want right before the </head> tag. After making the changes, save the file, and upload it back to the server.
6. That’s it! You’ve edited the file and changed the WordPress header of your site! You can verify the changes by viewing the website’s source code. It’s worth noting that this method has one main drawback.
Once you have changed the theme, you will lose all your previous customizations, so if you are planning to change themes in the future, this might not be the best option for you. On the other hand, if you need to modify your new theme’s header with the old code, a simple copy-pasting will do the job.
Bonus
Some WordPress themes like Newspaper, Newsmag, and others allow you to edit the theme header. Most WordPress themes come with a dedicated theme panel. From there, you can customize the theme. As an example, take a look at the theme panel offered by the Newspaper WordPress theme below.
To add the Google Analytics code, the team added a dedicated section to the panel.
The code will be added to the <head> section of your website. After adding the code, simply save the changes, clear your website’s cache, and you are good to go! If your theme doesn’t support this to edit the header, you can use one of the methods mentioned above.
What to add in the Header?
So now that you know how to edit your WordPress header, let’s have a look at what you can add to it:
- Google Analytics Tracking Code
- Verification Code
- Auto Ads Code
- Facebook Pixel
- Search Console Verification Code
- Mobile Bar Color Code
- Images and Videos
- Pinterest Verification Code
As you can see, almost every verification can be done through the header modification. Plus, if you need it, you can also add a widget to your header. This might be visible to your website visitors and it can be very useful because you can use the widget to add a CTA button, display advertising, or anything you want.
How to add an image to the header in WordPress
Another possible customization is to add images to the WordPress header. To do that simply follow these steps:
- Log in to your WordPress admin dashboard
- Go to Appearance > Header. Please note that some themes don’t have the header option so you’ll have to go to Appearance > Theme Editor > Header and modify the header PHP files
- Then, go to the Header Image section and click Add New Image
- After that, select the image you want to use in your header
- Then, you will go to the Crop Image section where you can decide what part of the image you want to display.
- Once you’re done, click Publish.
- That’s it! You’ve customized the WordPress header with a new image
When you add an image to your header, remember to:
- Use photos that catch the visitors attention and communicate what you do and your values
- Use pictures that fit your branding and are consistent with what you want to communicate. For example, if you’re a sports brand, don’t show pictures of fast food or cars. This might sound obvious but there are plenty of sites where the images don’t match what they do and end up confusing the costumers
How to add a video to the header in WordPress
For some businesses, it might make sense to add a video to the header to attract the users’ attention. So here, we’ll show you how to do it in 2 different ways.
- Add a YouTube video to the header
- Add an mp4 video
Let’s have a closer look at each method.
1) Add a YouTube video
Before starting with these steps, go to YouTube and copy the URL of the video you want to add to the WordPress header. After that, do the following:
- Log in to your WordPress admin dashboard
- Then, go to Appearance > Header
- There, go to the Header Media section and paste the URL of the YouTube video in the corresponding field under Header Video
- Press Publish and that’s it
2) Add an mp4 video
A second option to add a video to the WordPress header is to upload an mp4 video file. Keep in mind that the file can’t weigh more than 8 MB. Additionally, the dimensions will need to adjust to your theme’s container size. So, to add an mp4 video to the header, in the WordPress dashboard, you have to:
- Go to Appearance > Header
- Then, go to the Header Media section press Select Video under Header Video
- Search for the file and upload it to the Media Library
- Then press Choose Video and Publish it
- That’s it! You’ve added a video to the WordPress header!
NOTE: One advantage of the YouTube method is that it allows you to add any video, whereas if you upload a video file, the file can’t be bigger than 8 MB and it has to adjust to the theme sizes.
BONUS: How to access header tag in WordPress
The two easiest ways to access the tag to edit your header in WordPress are:
- From the WordPress dashboard: Go to Appearance > Theme Editor > header.php file. Near the top of the file, you should see the <head> and </head>. Simply add your code in between the tags.
- Via URL: Alternatively, you can access the header tag by adding /wp-admin/theme-editor.php?file=header.php to your domain URL. For example, for QuadLayers, it would be http://quadlayers.com/wp-admin/theme-editor.php?file=header.php.
If you use WordPress Network, you’ll need to use a different link: http://quadlayers.com/wp-admin/network/theme-editor.php (remember to change the URL with your domain)
What if my theme doesn’t have a header.php file?
Some child themes don’t have their own header.php files. If that’s your case, there are 2 options to customize your header:
- Move the parent theme’s header to the child theme and edit it from there
- Use a hook: To add code and edit your header you can add the following to the functions.php file of the child theme.
function QL_your_function() {
echo 'your code';
}
add_action( 'wp_head', 'QL_your_function' );
Note that this is an example code to give you a structure, you’ll need to adapt it and add your own code to it.
I’ve tried to edit the WordPress header but it didn’t work
Let’s say that you followed every step of this tutorial but the code wasn’t added to your site’s header. First, make sure you have edited the right file and added code to the right section. If you have done everything correctly and it still doesn’t work, there’s one simple solution. If you’re using a WordPress caching plugin on your site to optimize the speed and performance, simply clearing the cache will fix this issue in most cases.
Conclusion
To sum up, these are simple ways to edit the header of any WordPress website. For beginners, we recommend using the Insert Headers and Footers plugin because it is simple to use and manage.
On the other hand, if you are not planning to change your WordPress theme soon, editing the theme’s header.php file is an excellent choice for you.
Finally, it’s important to note that if you edited the header.php file of your WordPress theme and changed the theme, all the customizations will be lost although you can also copy and paste them. So, choose between the available options and find out which one is the best for you.
If apart from the header you also want to customize the footer of your site, check out our guide on how to edit the footer in WordPress.
Still, need help? Feel free to comment below and we will help you with whatever you need!