This article explains how to replace the native search bar in the Impreza theme by UpSolution.
Replacing is based on editing the Impreza child theme. Make sure you have installed the Impreza child theme. If not, install it.
Replacing is based on editing the the Impreza child theme theme. Make sure you have installed the Impreza child theme. If not, install it now. If you’re not sure how to install or activate the Impreza child theme, contact Impreza theme authors — https://help.us-themes.com/ or read this article.
Использование проверки на ABSPATH для предотвращения прямого доступа к PHP-файлам
Всё началось с того, что один подписчик из комментериев попросил меня оценить сайты, которые он делал, и в момент, когда я хотел через исходный код открыть файл style.css темы, я случайно открыл папку с темой, т.е. обратился напрямую к index.php .
В итоге вот что у меня открылось:
Ну прежде всего, конечно, я бы отключил константу WP_DEBUG в файле wp-config.php . После этого, при попытке прямого доступа к файлу, так же на 1-й строчке будет выдаваться ошибка 500 и ничего дальше в целом происходить не будет. В целом практически все файлы тем WordPress содержат функции WordPress, поэтому вероятность того, что кто-то сможет навредить вашему сайту, не очень большая. Разве что боты переполнят ваши логи, открывая сотни раз файл с ошибкой 500.
Поэтому тут может быть две рекомендации, первая – в начале PHP-файлов темы и плагина поместите эти строчки:
if( ! defined('ABSPATH')){die; }
Они означают, что если константа ABSPATH не определена (она определяется в файле wp-config.php ), то значит файл был запущен за пределами среды WordPress, а значит ничего не делаем и выходим из файла функцией exit() или die() . По логике вещей вы можете добавить эти строчки в начало каждого .php файла темы или плагина, которую вы разрабатываете. Однако, если вы скачаете какую-то тему или плагин WordPress, то заметите, что на практике так никто не делает, обычно проверку на константу ABSPATH мы находим только в тех .php -файлах, которые содержат классы (да и то не всегда).
Другая рекомендация – это запретить выполнение файлов PHP внутри темы или плагина, добавив следующую группу правил в файл .htaccess .
Order Deny,Allow Deny from all
В таком случае будем получать ответ Forbidden вместо ошибки 500. Тут важно быть осторожным, не содержит ли ваша тема каких-либо файлов PHP, к которым должен быть разрешён доступ напрямую (обработчики форм, вебхуки).
Ну и что делать то в итоге?
Для начала, если вам интересна история с разработкой плагинов и тем для WordPress, то могу порекомендовать мой курс по разработке темы и курс по разработке плагина!
Да в общем можно ничего не делать, главное не забывайте отключать WP_DEBUG после разработки. Ну и конечно, если это не обычный файл темы, который начинается с get_header(), убедитесь, что в файле нет ввода/вывода, который можно использовать при взломе, иначе проверка на ABSPATH обязательна!
Я проанализировал несколько самых популярных сайтов на WordPress и нашёл все три подхода!
CSS Tricks и WP Tavern – не делают ничего (файлы темы выдают ошибку 500),
WP Beginner – вероятно блокируют файлы при помощи файла .htaccess (получаем ответ Forbidden).
WP Explorer – используют константу ABSPATH (получаем пустой белый экран без ошибки – результат действия функции die ).
Миша
Впервые познакомился с WordPress в 2009 году. Организатор и спикер на конференциях WordCamp. Преподаватель в школе Нетология.
Пишите, если нужна помощь с сайтом или разработка с нуля.
Integration is the process of inserting the Groovy menu into your site.
PHP code
To manually integrate the Groovy menu into your theme, you’ll need to copy PHP code from the Groovy menu > Integration section and paste it into the appropriate template in your theme.
Note. Groovy menu creates its own menu location called Groovy menu Primary which can be found at Appearance > Menus > Manage Locations
Header.php
The exact location in your theme’s code where th PHP code should be inserted will depend on your theme. However, the most common location is the header.php
We recommend making such changes only in the child theme; otherwise, your changes will disappear after updating the theme.
If you’re experiencing any issues during the integration process, please create a support ticket through Help desk.
How to change wrapper tag
How to manually integrate the Groovy Menu plugin into a child theme that is itself a child theme of another theme?
During manual integration of the Groovy Menu, we recommend using Child themes (What is a child theme). This will ensure that any changes you make are not lost when updating your WordPress theme.
However, there may be situations where the Child theme is already being used as the main theme and is updated from the developer’s repository. Editing such a theme may result in loss of changes if the theme will be updated.
If you are have installed such theme as Genesis or Primer, then you are already using a child theme.
Editing such a theme may result in loss of changes if the theme is ever updated.
In such cases, instead of editing a child theme, you can create a Grandchild theme.
This is similar to creating a child theme, except that you do it through a specail plugin. You can add your custom functions to the plugin, just as you would in functions.php (although it’s important to note that your plugin will be called much earlier than functions.php, so any code in your plugin should only execute when the corresponding action is being executed).
Bellow we provide example of such plugin.
Integration mega menu trough a plugin
function gts_grooni_add_to_primary_navigation() < if ( function_exists( 'groovy_menu' ) ) < groovy_menu(); >>
Integration through shortcode
You can use the [groovy_menu] shortcode to output the Groovy Menu. Simply paste the shortcode where you would like the menu to appear.
Переадресация на другую станицу с контактной формы
Прошу помочь опытных пользователей. Есть сайт на котором установлена контактная форма. После нажатия «Ок», я получаю e-mail и телефон клиента, а пользователь сайта получает сообщение об успешной отправки информации. Нужно вместо сообщения, настроить автоматический перевод клиента на другую страницу сайта после нажатия «Ок» и отправки контактных данных. Код контактной формы на сайте:
defined('ABSPATH') OR die('This script cannot be accessed directly.');/*** Contact form configuration** @filter us_config_cform*/returnarray('fields'=>array('name'=>array('type'=>'textfield','title'=>'','placeholder'=> us_translate('Name'),'error'=> __('Please enter your Name','us'),),'email'=>array('type'=>'email','title'=>'','placeholder'=> us_translate('Email'),'error'=> us_translate('Please enter a valid email address.'),),'phone'=>array('type'=>'textfield','title'=>'','placeholder'=> __('Phone Number','us'),'error'=> __('Please enter your Phone Number','us'),),'message'=>array('type'=>'textarea','title'=>'','placeholder'=> __('Message','us'),'error'=> __('Please enter a Message','us'),),'captcha'=>array('type'=>'captcha','title'=> __('Just to prove you are a human, please solve the equation: ','us'),'placeholder'=>'','error'=> __('Please enter the equation result','us'),),'checkbox'=>array('type'=>'checkbox','title'=>'','placeholder'=>'','error'=> __('You need to agree with the terms to proceed','us'),),),'submit'=> __('Send Message','us'),'success'=> __('Thank you! Your message was sent.','us'),'error'=>array('empty_message'=> __('Cannot send empty message. Please fill any of the fields.','us'),'other'=> __('Cannot send the message. Please contact the website administrator directly.','us'),),'subject'=> __('New message from %s','us'),);