Многие из наших пользователей спрашивают у нас: что такое "дочерняя тема" в WordPress? В этой статье мы ответим на этот вопрос, а также поясним когда вы должны создавать дочернюю тему, ее преимущества и недостатки.
Что такое дочерняя тема в WordPress
A WordPress child theme is a WordPress theme that inherits its functionality from another WordPress theme, the parent theme. Child themes are often used when you want to customize or tweak an existing WordPress theme without losing the ability to upgrade that theme. In the past, there was no easy way of updating WordPress themes without losing all the custom styling and changes that you had made. This becomes chaos when all the sudden you find out a widely used script in popular themes has a major exploit, and you need to update your themes ASAP. Это становится проблемой, потому что, с одной стороны, вы потеряете все пользовательские стили при обновлении. С другой стороны, ваш сайт могут взломать, если вы не будете устанавливать обновления.
В теории, любая тема WordPress может иметь дочерние темы, однако, не все родительские темы хороши. Родительская тема с ограниченными функциональными возможностями и функциями - не совсем идеальный кандидат в родительскую тему. Хорошие родительские темы, также известные как фреймворк-темы как правило, содержат свои собственные хуки и фильтры.
Для чего в WordPress нужны дочерние темы?
Дизайнеры и разработчики используют дочерние темы, чтобы ускорить разработку сайта. При использовании хорошей родительской темы, вы можете значительно сократить время, необходимое для создания сайта в WordPress, поскольку темы предлагают тонны функционала и настройки опций, так что вам не нужно кодировать все с нуля. Разработчики часто создают дочерние темы, чтобы настроить существующую тему, не теряя возможности обновлять родительскую тему в случае необходимости.
Создание дочерней темы в WordPress настолько же просто, как и создание нового файла style.css в новой папку. Все, что вам действительно нужно, - это одна строка в заголовке style.css файла, которая определяет шаблон Theme Name: Имя_шаблона
. A robust child theme can have just as many template files as the parent theme if not more. Дочерняя тема может иметь файлы шаблонов, которые не доступны даже в родительской теме.
Когда использовать дочернюю тему в WordPress
Решение использовать дочернюю тему часто зависит от ваших потребностей. В редких случаях, когда проект слишком сложен или слишком прост, мы строим его как отдельную пользовательскую WordPress-тему. Как разработчики WordPress, мы должны оптимизировать наш рабочий процесс, создавая качественные темы.
For users we recommend child themes only if you find yourself constantly adding new functions to your theme’s functions.php file and/or constantly adding/modifying the style.css file of your theme. В этих случаях, мы настоятельно рекомендуем вам использовать дочернюю тему. A short while ago during our WordPress meetup talk, one of the members asked us what if you are only adding custom styles? Что лучше использовать дочернюю тему или пользовательский CSS плагин?
Ответ на этот вопрос зависит от здравого смысла и комфортно ли вам с этой технологией. Если вам нужно лишь изменить стили нескольких элементов, то используйте пользовательский CSS плагин. Тем не менее, you find yourself changing the entire color scheme, moving things around in the CSS и т.д., то вы определенно должны рассмотреть возможность использования дочерней темы. Проще говоря, вы должны использовать дочернюю тему когда вам нужна функциональность, возможности и мощь родительской темы без самостоятельного написания большого количества кода.
Преимущества использования дочерней темы в WordPress
Like most things, there are advantages and disadvantages to using a WordPress Child theme. Let’s take a look at advantages first.
1. Безопасные обновления
A child theme automatically inherits the parent theme’s features, styles, and templates. This allows you to make changes to your site using child themes without ever modifying the parent theme. When a new version of the parent theme arrives, you can safely update it as all your modifications are saved in the child theme.
2. Легкая расширяемость
A child theme built on a powerful theme framework allows a great deal of flexibility without writing a lot of code. You can selectively modify only the template files and functions that you need without going through other template files. You can add new functionality and much more.
3. Fallback Safe
When you are creating a complete theme you need to think about all the possible scenarios and code for them. However, when you are working on a child theme and you forget to code for something, then there is always the parent theme’s functionality available as the fallback option.
Недостатки использования дочерней темы
One of the biggest disadvantage of using child themes is the time you need to invest to learn about the parent theme. There is a learning curve specially when you are working with robust frameworks because each of them have their own hooks and filters. You really have to know those to maximize the potential. In our opinion, this learning curve is a one-time thing. Например, создание первых нескольких дочерних тем, которые вы создаете, займет у вас большое количество времени, но после того, как вы набьете руку, ваша производительность увеличится.
Another disadvantage often pointed out is that your parent theme’s developers may loose interest and abandon it, drop a feature that you were using in your child theme, or bring a change that totally destroys your child theme. This is not as bad as it sounds. Mainly because all good WordPress themes are open source and GPL. If the parent theme developer abandons the project, then nothing says that you have to stop using it. Often times, other folks in the community step up to take over the project. If the original theme developers remove a certain feature, then you can simply add it in your child theme. You have the code for it. Lastly, if they make a drastic change that you don’t like, then you can always avoid updating. Theme updates are crucial when there is a security exploit. We always recommend users to update themes because it helps ensure future compatibility with other scripts and plugins.
If you are using a commercial theme framework like Genesis, then you have support option available to help you upgrade your theme or troubleshoot problems. Also a platform like Genesis is not going to just disappear because there is a stable business organization behind it with thousands of customers world wide. For example, they removed certain built-in widgets, but they made them publicly available as plugins for those who still wanted to use it.
Conclusion
It is important to know that even though you can always create a child theme of any WordPress theme, sometimes you may not need a child theme. Think about the number of changes you have planned for your child theme, if the changes you are planning are minor, then you can always create a custom-style.css
file in your theme or use a Custom CSS plugin. If the changes are too extreme where you find yourself overriding the core parent theme files, then you probably should be creating a custom theme.
We hope that this article helps you understand what is WordPress Child Theme and whether it is a good fit for you or not. If you think we missed something, then please let us know in the comments below.