Как вставить PHP код в WordPress

Здравствуйте, дамы и господа! Сегодня мы рассмотрим с вами как правильно добавлять/вставлять в functions.php WordPress код PHP, то есть, безопасным и практичным способом. Не спешите редактировать файл functions.php. Есть гораздо более безопасные способы вставки своего кода в данный файл. В этом руководстве я покажу вам простой способ добавить / вставить собственный PHP код WordPress. Без редактирования файла functions.php и не нарушая работу вашего сайта WP (ВордПресс).

В некоторых случаях вам может понадобиться добавить новую функцию на свой веб-сайт, либо подключить что-либо к теме WP.
Сделать это можно разными способами: вставить PHP код WordPress напрямую в файл functions.php вашей темы (не безопасно и не практично). Или с помощью специального php плагина WP (легко, быстро, надёжно и безопасно).
Совет: Если вы редактируете файл functions.php, используемую в настоящий момент, подумайте о возможном нарушении работоспособности сайта.
При обновлении темы сделанные вами изменения будут перезаписаны. Чтобы избежать этого, можно создать дочернюю тему.
Файл functions.php WordPress
Файл functions.php предназначен для функционала, связанного с темой или внешним видом сайта WordPress. Кому интересно, вы можете почитать статью Константина Ковшенин (разработчик в компании Automattic) — о файле functions.php .
Файл WordPress functions.php является одним из наиболее важных файлов любой установки WordPress. Он может контролировать большую часть функциональности и поведения вашего сайта. Этот файл может быть использован для добавления ваших собственных фрагментов кода в WordPress. Файл functions.php WordPress вы можете найти в Внешний вид — Редактор тем:

Вы можете использовать functions.php для добавления любых функций на ваш сайт (как это делают плагины). Однако новички часто не знают, как безопасно добавлять код в functions.php в WordPress. Обычно в статьях по WordPress вы найдете фрагменты кода с инструкциями (из уроков без плагина) по вставке их в файл functions.php темы или в плагин для конкретного сайта напрямую. Мол «необходимо будет вносить правки в файл функции темы сайта (functions.php)». Так делать не рекомендуется.

Проблема в том, что даже малюсенькая ошибочка в пользовательском PHP коде может поломать ваш сайт и сделать его недоступным. Или файл functions.php становится большим (сборная солянка) и не читаемым, а при смене активной темы пропадает часть функционала, которая вовсе не относится к внешнему виду сайта.
Безопасное добавление фрагментов кода в файл functions.php с помощью бесплатных плагинов.
Как добавить / вставить PHP код в WordPress
Универсальный способ добавить код в functions.php WordPress — это использовать плагин My Custom Functions, Code Snippets или создать собственный. Они решают задачу интеграции PHP функций, и добавляют их так, будто они были написаны в файле темы functions.php. При этом ни обновление темы, ни даже её изменение на новую, данную интеграцию не нарушают.
My Custom Functions — плагин WordPress
Что в переводе означает — Мои пользовательские функции. Незаменимый инструмент для авторов и владельцев сайтов. Простой в использовании плагин WordPress с интуитивно понятным интерфейсом. My Custom Functions даёт вам возможность легко и безопасно добавлять свой собственный PHP-код на ваш сайт WordPress прямо из админ панели WordPress. Расширение переведён на русский язык. Скачали более 769 063 раз.

Больше не нужно редактировать файл functions.php вашей темы или какой-либо из ваших файлов плагинов для добавления собственного кода PHP. Просто добавьте свой собственный PHP-код в поле на странице плагина, и этот плагин сделает все остальное за вас. Он автоматически добавит ваш PHP-код на ваш сайт, без изменения каких-либо файлов вашей темы и без замедления вашего сайта.
Плагин работает полностью независимо от темы, поэтому вы можете использовать его с любой темой и независимо от того, имеет ли тема файл functions.php или нет. Код, который вы разместите на странице плагина, не изменится, если вы отредактируете содержимое файла functions.php темы или даже полностью измените тему.
Это действительно полезно в случае обновления темы или плагинов WordPress, потому что ваш собственный PHP-код никогда не будет перезаписан. Ваш собственный PHP-код будет продолжать работать независимо от того, сколько раз вы обновляете или переключаете тему и плагины.
Установка плагина My Custom Functions
Установите «Мои пользовательские функции» так же, как и любой другой плагин WordPress. Автоматически через админку WordPress. Плагины — Добавить новый. Найдите плагин через поиск. Установите и активируйте его:

После установки и активации в разделе Настройки появится пункт PHP Inserter. Кликните по нему, откроется страница настроек плагина My Custom Functions:

На странице плагина вы найдете редактор кода на базе CodeMirror. Этот редактор кода имеет такие параметры, как выделение синтаксиса, нумерация строк и многое другое.
Вставка кода PHP в WordPress
Чтобы добавить свой собственный PHP-код на свой веб-сайт, просто выполните следующие действия: на вкладке Главная, вставьте свой собственный код PHP в поле редактора.

Установите переключатель в положение ON (Включить) и нажмите кнопку «Сохранить изменения». Наслаждайтесь результатом применения вашего собственного кода PHP. Это так просто! Да, если будите добавлять ещё один код, тогда сделайте один пробел после первого и вставляйте следующий.
Можно ли использовать код HTML / CSS / JS, интегрированный в код PHP? Да, можно. Но делать это нужно правильно, вот так:
Пока не забыл, поделюсь. На скриншоте добавлена функция только один логин на пользователя. Для чего это?
У вас есть сайт WordPress на основе платной подписки (членство)? И пользователи могут делиться своей учетной записью со своими друзьями или кем угодно, что делает ее для них бесплатной. Но вы этого не желаете.
Вы хотите, чтобы к одной учетной записи мог входить только один человек. Можно реализовать функцию, которая предотвращает одновременный вход в систему более одного пользователя.
Для этого PHP код:
Переходим к следующему плагину. Он мне нравится больше и я его использую на двух моих блогах. Шикарный модуль.
Плагин Code Snippets (фрагменты кода)
Code Snippets — это понятный и простой способ запускать фрагменты кода PHP на вашем сайте. Это устраняет необходимость добавлять в ручную пользовательские фрагменты в functions.php файл вашей темы. Более 1 704 005 установок.

Плагин Code Snippets позволяет использовать на своём сайте сниппеты кода (хуки, хаки и другие), не редактируя файлы темы functions.php. Такой метод имеет много преимуществ – при обновлении темы код пользователя не теряется, нет необходимости в создании дочерних тем, хаки работают на любой теме.
Code Snippets предоставляет графический интерфейс, аналогичный меню Plugins, для управления сниппетами. Фрагменты можно активировать и деактивировать, как и плагины. Редактор фрагментов включает поля для имени, описание с поддержкой визуального редактора, теги, позволяющие категоризировать фрагменты, и полнофункциональный редактор кода.
Установка плагина Code Snippets
Первое, что вам нужно сделать, это установить и активировать плагин Code Snippets на своем сайте. Как обычно, устанавливаем стандартным способом. Плагины — Добавить новый. Вводите его название в поле поиска. Пару раз нажимаем Установить и Активировать:

После активации плагин добавит новый пункт меню с надписью Сниппеты (Snippets) в панель администратора WordPress. Нажав на нее, вы увидите список всех фрагментов пользовательского кода. По умолчанию в плагине добавлены фрагменты кода для примера. Это:
- Как добавить HTML шорткод.
- Как добавить CSS шорткод.
- Как добавить код JavaScript на сайт WordPress.
Они все деактивированы. Не удаляйте их. Они могут пригодится вам в качестве инструкции, как встроить HTML, CSS и JavaScript в PHP код:

Сниппеты — они как плагины, и те и другие расширяют функциональность WordPress. Snippets обычно имеют гораздо меньший размер, пару строк кода, и обычно менее нагружают хостинг. На странице можно управлять имеющимися сниппетами, активировать, деактивировать, удалять или экспортировать их.
Этот плагин предоставляет графический интерфейс для управления сниппетами, что упрощает добавление кода.
Как добавить фрагменты PHP кода в functions.php WordPress
Кликните на пункт Добавить новый. Для добавление сниппета нужно заполнить поля названия и кода. Обязательно укажите заголовок для фрагмента кода. Таким образом, вы сможете легко идентифицировать коды в будущем:

После присвоения фрагменту имени и добавления PHP кода вы также можете написать описание, которое поможет вам запомнить цель кода, где вы его нашли и почему вы добавляете его на свой веб-сайт. Это может быть полезно другим пользователям, которые работают над вашим сайтом сейчас или в будущем:

После этого, нажмите Сохранить изменения и активировать. Будьте внимательны, перед добавление сниппета убедитесь в том, что он является корректным PHP кодом, и не приведет к сбоям. Хотя добавляемый Snippets сразу не активизируется, это поможет сократить вероятность включения не исправного сниппета в будущем.
Как было уже сказано, вы можете легко управлять своими фрагментами PHP кода, включать, выключать, редактировать, удалять, клонировать или экспортировать их.

Как вы можете видеть, очень удобный и шикарный plagin. Не даром он самый популярный в каталоге wordpress.org. И ещё, друзья, если вам нужно лишь вставить небольшой отрывок кода и вы не хотите использовать чужие плагины тогда, рассмотрите простой вариант — создайте свой собственный / личный, коротенький плагин.
Как создать свой плагин дополнительного файла functions.php
Хорошим решением будет создать свой кастомный мини плагинчик.
Если нужно добавить на сайт свои пользовательские функции, но при этом вам не хочется устанавливать предложенные готовые модули или разбираться с дочерними темами, то сделать это можно при помощи своего личного плагина. Создаём плагин — отдельный файл функций для сайта WP. Создайте файл с кодом:
Сохраните данный файл в формате PHP с уникальным названием например, my-functions.php и загрузите его в директорию wp-content/plugins. Никакая пара используемых плагинов не должна иметь одинаковое имя файла. Далее перейдите в раздел Плагины в панели администрирования WordPress и просто активируйте его:

Обратите внимание, что имя плагина будет таким, которое прописано в информационном заголовке Plugin Name: Моя альтернатива файлу functions.php . Естественно вы можете изменить его, в созданном файле, на своё. Всё.
А давайте создадим настоящий плагин как положено, со стандартной информацией о нём:
Впишите / замените на свои данные. Разместите нужный вам PHP — код в размеченной области. Для удобства загрузите заготовку плагина — Скачать. Установите его как обычно и активируйте. Вот он наш родной:

Редактировать и вносить изменения в созданный плагин можно прямо из админки. Плагины — Редактор плагинов. Выбираете по названию например, My Custom Functions:

Чтобы добавить свой фрагмент кода, просто вставляйте его в файл .php, который вы создали.
How can I add a PHP page to WordPress?
I want to create a custom page for my WordPress blog that will execute my PHP code in it, whilst remaining a part of the overall site CSS/theme/design.
The PHP code will make use of third-party APIs (so I need to include other PHP files).
How do I accomplish this?
N.B.: I do not have a specific need to interact with the WordPress API — apart from including certain other PHP libraries, I need I have no other dependencies in the PHP code I want to include in a WordPress page. So obviously any solution that didn’t require learning the WordPress API would be the best one.
![]()
19 Answers 19
You don’t need to interact with the API or use a plugin.
First, duplicate post.php or page.php in your theme folder (under /wp-content/themes/themename/ ).
Rename the new file as templatename.php (where templatename is what you want to call your new template). To add your new template to the list of available templates, enter the following at the top of the new file:
You can modify this file (using PHP) to include other files or whatever you need.
Then create a new page in your WordPress blog, and in the page editing screen you’ll see a Template dropdown in the Attributes widget to the right. Select your new template and publish the page.
Your new page will use the PHP code defined in templatename.php
![]()
If you wanted to create your own .php file and interact with WordPress without 404 headers and keeping your current permalink structure there is no need for a template file for that one page.
I found that this approach works best, in your .php file:
Then you can simply perform any WordPress functions after this. Also, this assumes that your .php file is within the root of your WordPress site where your wp-config.php file is located.
This, to me, is a priceless discovery as I was using require_once(dirname(__FILE__) . ‘/wp-blog-header.php’); for the longest time as WordPress even tells you that this is the approach that you should use to integrate WordPress functions, except, it causes 404 headers, which is weird that they would want you to use this approach. Integrating WordPress with Your Website
I know many people have answered this question, and it already has an accepted answer, but here is a nice approach for a .php file within the root of your WordPress site (or technically anywhere you want in your site), that you can browse to and load without 404 headers!
Update: There is a way to use wp-blog-header.php without 404 headers, but this requires that you add in the headers manually. Something like this will work in the root of your WordPress installation:
Just to update you all on this, a little less code needed for this approach, but it’s up to you on which one you use.
How to Add & Edit Code in WordPress (HTML, CSS, PHP)
One of the main draws of using WordPress is that you can build websites without touching a line of code, but you still have the full freedom to edit source code if you wish.
If you know how to add code to WordPress safely, you can change your website design and functionality to make your work a lot easier. What type of code you decide to insert is up to you. In WordPress, you’ll usually deal with HTML, CSS, and PHP.
In this article, we’re going to tell you what to do before you start adding and editing code in WordPress. Then we’ll show you how to insert HTML, CSS, and PHP into your website. We’ll cover multiple approaches to adding and editing code for each language.
What to do before you edit code in WordPress
Editing existing code within your site’s core files or making additions to them always carries a risk. If there are errors or you break existing functions, your website might stop working.
It’s possible to fix a website with errors in its code. But unless you have development experience, narrowing down the exact code that’s causing problems can be a challenge.
With that in mind, we recommend that you take several steps to secure your website before you start adding or editing code. Think about this process as creating a safe environment to avoid problems down the road.
1. Back up your website
No matter the type of site you have, backups are absolutely critical. Why? Because if something goes wrong — a hack, plugin conflict, or code error — you can simply restore a recent backup to get your site up and running again.
In other words, backing up your site is the best way to protect your website if anything goes wrong.
To make this process easy, it’s best to use a plugin to automatically take care of everything or generate copies of your website on demand.
Of course, we recommend Jetpack Backup — a complete solution that works in real-time.

With Jetpack, backups are securely stored off-site in the cloud, so there’s no load on your server. And since a backup is taken every single time something changes on your site, you can quickly restore one from right before an error occurred, even if your site is completely offline.
If you choose to use another backup plugin, however, we recommend taking a full manual backup before continuing with the steps below.
2. Use a WordPress child theme
This measure only applies if you plan to edit your theme. WordPress enables you to make any changes that you want to any theme’s code, but when you update to a new version of a theme, any customizations will be lost.
To prevent this, you’ll need to use a child theme. A child theme is a secondary theme that pulls in features, functionality, and styles from its parent theme, but that doesn’t change when you update the parent. This means that the code you add to the child theme won’t be erased when you update the parent theme.
While you can create child themes manually, we recommend using a plugin instead. One of the best tools for the job is Child Theme Configurator.
Activate the plugin and go to Tools → Child Themes. Select the option to create a new child theme and select your current theme as the parent.

Click on Analyze, and the plugin will check to see if it can create a child theme for your selection. Under Select where to save new styles, choose the Primary Stylesheet option.
For the Select Parent Theme stylesheet handling option, click on Use the WordPress style queue.

You can also customize the child theme’s attributes. These include the name, author, and description that will appear when you navigate to Appearance → Themes.

The attributes you choose are for internal use only. Once you’re happy with the settings, click on Create New Child Theme.
If you navigate to Themes → Appearance, the new child theme should appear among the available themes.

Once the child theme is set up, you can start adding custom code to it. If you’re not sure how that process works, keep reading. We’ll show you how to edit CSS and HTML in WordPress in the following sections.
3. Use a staging website
The entire purpose of a staging website is to help you test new code and changes to your site in a safe environment. With a WordPress staging site, you can add code without having to worry about critical errors or downtime on your live website.
Typically, your web host will offer staging functionality. There are several options for WordPress staging plugins, but they can be a bit awkward to use. If you can access staging functionality through your hosting control panel, it will be much easier to create copies of your site and push changes from staging to production.
How to edit HTML, CSS, and PHP code in WordPress (10 methods)
Learning how to edit code in WordPress is much easier than you might think. Still, the process will change depending on which type of code you want to use. Let’s start by talking about adding HTML using the Block and Classic Editors.
1. How to edit HTML in the Block Editor
This method allows you to edit any existing page or post using HTML within the Block Editor. It’s a straightforward method that shouldn’t pose any issues if you’re familiar with the Block Editor.
To get started, open the editor. Once you can see the body of the page or post, click on the three-dot icon in the top-right corner of the screen.

Now click on the option that says Code editor.

The view in the body of the editor will switch from blocks to code. For each block, you’ll see a different section of HTML code.

Keep in mind that WordPress code editors don’t include any highlighting functionality. That means all code will appear as plain text. You’ll need to read carefully if you want to change or add to it.
You can switch back and forth between the visual and code interfaces in the Block Editor. When you’re happy with the results, save the changes to your post or page.
2. How to edit HTML in the Classic Editor
Editing HTML code using the Classic Editor is straightforward. Open the page or post that you want to work on and locate the Text tab above the body of the document.

Click on the Text tab, and you’ll see the contents of the Visual tab appear in plaintext format. By default, any text that you add without formatting won’t include any HTML code.
You can quickly add formatting and HTML code using the buttons at the top of the editor. The Classic Editor includes options for bold or italicized text, links, images, lists, and other types of code.
There’s also the option of adding HTML code manually. If you’re familiar with HTML, you can insert or edit it within the Text tab as you wish. The editor enables you to switch back and forth between the Visual and Text tabs to see the results.
3. How to edit HTML using the Theme Editor
WordPress lets you access and edit theme files directly from your dashboard. But if you plan on editing theme files, we recommend setting up a child theme beforehand.
To access the theme editor, go to Appearance → Theme file editor. On the next page, you’ll see a plaintext editor to the left and a list of files to the right. That list of files corresponds to the theme that you choose from the top-right dropdown menu.

By default, the theme editor will open with the Style.css file for the theme you’re working on. Most of the theme files you can access using the editor involve either CSS or PHP. But you can edit several theme components using HTML.
However, in most cases, child themes only pull in the style.css and functions.php files by default. So if you want to edit an HTML file, like footer.html, you’ll need to copy it over to the child theme before making any changes using a file transfer protocol (FTP) tool or your hosting provider’s control panel.
Using your tool of choice, go to public_html → wp-content → themes → your parent theme. Find the HTML file you want to edit and copy it to your child theme’s folder. Then, that file will be visible in the WordPress Theme Editor.
You can find your HTML files in the Theme Editor by selecting your child theme from the dropdown at the top right of the page, then clicking on the file from the list that appears.

We recommend not making any changes when you’re editing theme files unless you precisely understand what your code does. Otherwise, you risk breaking critical features within the theme and your website.
4. How to edit CSS and PHP in the Theme Editor
To access the WordPress theme editor, go to Appearance → Theme file editor. You’ll see a list of the files that you can edit for your active theme on the next screen. To the left, you’ll see an editor tab displaying the contents of the file that you select.
By default, the theme editor will open to a stylesheet. The style.css file will contain all the CSS stylings for the theme. These include classes, IDs, button styles, and much more.
You can make any changes that you want to the style.css file. When you’re done, click Update File to save the changes.
That same process applies to PHP files. Select the .php file that you want to edit using the menu to the right. In this example, we’re editing the functions.php file.

Editing PHP code can be more delicate than working with HTML or CSS. With the latter, if you make an error, it can affect your website’s styling. In contrast, PHP code that doesn’t work can lead to broken functionality.
5. Editing HTML in a WordPress widget
As you may know, recent versions of WordPress enable you to edit widgets using blocks. That means instead of classic widgets, you can use the full suite of Block Editor elements in your widgetized areas.
To edit your widget areas, go to Appearance → Widgets. Here, you’ll be able to edit the available widget sections for your theme.

Some blocks can add custom HTML to your widget areas. Click on the plus sign button next to the Widgets heading and select the Custom HTML block.

Add the code you want within the block and move it around to change its placement. When you’re done, click on the Update button in the top-right corner of the screen.
6. Editing HTML through cPanel
If your web host offers a cPanel installation for your account, you can use it to manage and edit your website’s files.
To get started, log in to your cPanel account and look for the File Manager option under FILES.

The File Manager enables you to navigate your hosting account’s files. Depending on your server’s structure, you might find yourself facing several folders.
Look for the option that says public_html or www. Those directories should contain your WordPress site’s files.

This is called the WordPress root directory. Once you open it, you’ll find several subdirectories and files corresponding to your WordPress website. If you right-click on any of these files, you’ll see an Edit option.

Clicking on that option will launch the cPanel text editor. This editor is very barebones compared to any software installed locally. We only recommend that you use it to make minor HTML edits.
For more complex code updates, you’ll want to use File Transfer Protocol (FTP) and a local text editor. We’ll show you how to do that in the next section.
7. Editing HTML, CSS, and PHP using FTP
FTP enables you to connect to your website’s server so you can edit and upload files. With FTP, you can easily upload large numbers of files. This process would be time-consuming and difficult if you tried to do it directly through the WordPress dashboard.
More importantly, FTP can edit WordPress files and add HTML, CSS, or PHP code using any local text editor of your choice.
To connect to your website via FTP, you’ll need a client (like FileZilla) and a set of credentials. Most web hosts provide you with FTP credentials at signup. If not, you should be able to create a new FTP account through the hosting control panel.

Enter your FTP credentials into your preferred FTP client and connect to the server. Once you establish a connection, you’ll see a list of folders and files.
With an FTP connection, you get full access to every file and folder within your account. To find your WordPress files, look for the directory called public, public_html, or www. Those are the most common names for the WordPress root directory.

Open the directory and locate the file that you want to edit. Right-click on it and select the option that says Edit. In these examples, we’re using FileZilla, so the menu reads View/Edit.

The View/Edit option will open the file using your local default text editor. Unlike cPanel or WordPress, dedicated editors make adding and interacting with code much easier.
In this example, we’re editing wp-config.php, which is a WordPress core file.

You can add or edit any type of code that you want using a text editor. That includes HTML, CSS, and PHP. The only limitation is your knowledge of each particular language.
Once you finish adding or editing WordPress code, save the changes to the file and close it. Your FTP client will ask if you want to override the existing version of that file on the server. Select Yes, and that’s it.
8. Adding CSS classes using the Block Editor
If you want to use CSS to customize the appearance of blocks, the Block Editor lets you add classes to any element. This process is also very straightforward.
To add CSS classes to a block, click on it and open the Settings tab. Then, look for the Advanced tab at the bottom of the block settings.

You can use the Additional CSS class(es) field to add one or more CSS classes to any specific block. The effect those classes will have depends on the WordPress custom CSS that you add.
9. How to edit CSS in the WordPress Customizer
The WordPress Customizer can make sitewide changes to your website’s style and layout through a visual interface.
To access the Customizer, go to Appearance → Customize. On the next screen, you’ll see a menu to the left and a preview of your site to the right.

The Additional CSS tab will give you access to a basic editor to add custom CSS to your website.

Adding CSS using the WordPress customizer lets you preview the changes instantly.
10. Editing CSS using a WordPress plugin
Some WordPress plugins offer alternative methods for adding custom code to WordPress. In most cases, these plugins focus on helping you add WordPress custom CSS or JavaScript.
One example is Simple Custom CSS and JS. This particular plugin can add custom CSS, JS, and HTML code to WordPress from a simple menu.

Selecting the Add CSS Code option will open an editor. You can use that editor to insert custom CSS and choose where the code will go within your files.

Although adding custom CSS with plugins is simple, we recommend against this method. WordPress provides you with plenty of built-in options for adding and editing CSS code. If you want a more hands-on approach, you can always use FTP.
If you rely on a plugin to add custom CSS, the code might disappear if you uninstall the plugin. Furthermore, different plugins will add code using unique methods, so your results will vary depending on which tool you use.
Can you add JavaScript code to WordPress?
WordPress doesn’t provide any built-in functionality for adding JavaScript code to your website. Unlike with HTML and CSS, your only options with JavaScript are to use plugins or add the code manually through the theme editor or FTP.
Usually, the easiest way to add JavaScript code is to use a plugin. If you choose the manual approach, you can use JavaScript with WordPress with the PHP “enqueueing” function.
Should you optimize your WordPress code for better performance?
Code optimization is a broad term that encompasses several practices. These ensure that your code runs as smoothly as possible and doesn’t take up a lot of server space.
By and large, code snippets shouldn’t take up too much storage. Still, you can reduce the space they occupy using “minification.”
Minification takes your custom HTML and CSS and removes empty spaces or unnecessary characters. To give you an example, here’s a simple custom CSS snippet:
If you take that code and minify it, it’ll look something like this:
The output of the code remains the same, but the resulting file size can be smaller. In practice, minifying HTML and CSS code often won’t provide you with significant results.
The exception is when you’re dealing with massive code libraries. Any size reduction will lead to shorter loading times for visitors.
In addition, choose your third-party code source carefully. Relying on reputable websites and expert developer forums can ensure that your code is effective, safe, and functional. In contrast, random snippets from unknown blogs are more likely to cause issues, slow down your site, and potentially break it.
Customize WordPress using HTML, CSS, and PHP
Learning to add and edit code in WordPress is easier than you might think. Even if you’re not a developer, you can often find code that fits your needs with a quick bit of Googling. Knowing how to insert that code safely can enable you to customize your website in ways plugins alone might not be able to.
Before you start making any changes to your site’s code, we recommend creating a full backup. If you’re going to edit your theme’s CSS or PHP, you’ll also want to use a child theme. Depending on which web host you’re using, you might also have access to staging functionality. We recommend using a staging website when editing code for safety purposes.
Simon has worked in marketing and product development for over 10 years, previously at HubSpot, Workday, and now Automattic (Jetpack). He has a varied education, with a degree in chemical engineering and a masters in computer science to his name. His passion is helping people and their businesses grow.
Explore the benefits of Jetpack
Learn how Jetpack can help you protect, speed up, and grow your WordPress site.
Реализация идеи
1. Создадим php-файл. Я назвал свой «test.php» и добавил его в корневой каталог с загруженной темой, вот сюда:
Должно получится следующим образом:
2. Для использования всех функций WordPress необходимо подключить «wp-load.php», вставляем приведенный ниже код в наш PHP:
3. Для примера добавляю в php-файл функцию получения временной зоны сайта с выводом на странице:
В итоге мой файл выглядит следующим образом:
В принципе, все готово, теперь можно переходить по ссылке ниже:
Но блин, какая длинная ссылка получилась, это ведь не удобно! Давайте сократим ссылку и создадим человекоподобный URL (ЧПУ). Например, чтобы страница открывалась по короткому урл:
4. Находим в корневой папке WordPress файл «.htaccess», при помощи которого можно задавать различные настройки сервера apache и открываем его редактором.
5. Добавляем директиву «RewriteRule» после «RewriteBase»:
У меня это выглядит так:
6. Переходим в браузере по заданному URL и видим, что страница отображается и функция отображения часовой зоны работает.
Готово! И никакие плагины не нужны! Естественно существует огромное множество плагинов, чтобы это реализовать, но в них еще нужно разобраться, а можно за несколько шагов, описанных в статье, сделать самому.