Все про файл functions.php для вордпресс
Файл functions.php для WordPress неоднократно упоминался в данном блоге при решении тех или иных задач. Однако при этом я говорил о нем вскользь, подразумевая, что вы хорошо знакомы с его работой. Сегодня же наоборот, решил детально рассмотреть все нюансы, которые касаются файла функций functions.php: зачем он вообще нужен, как правильно и безошибочно с ним работать и т.п. Инструмент на самом деле весьма актуальный как при работе с админкой, так и в процессе редактирования темы. Пусть информация и немного теоретическая, почитать будет полезно (особенно новичкам).
Статья имеет 3 подраздела:
Что такое файл functions.php и зачем он нужен?
Как правило, в данном файле задаются дополнительные функции для шаблона, позволяющие менять внешний вид вашего сайта. Однако на самом деле его возможности значительно шире, поскольку functions.php в WordPress автоматически загружается при инициализации системы. То есть при вызове любой страницы, как фронтенда (сайта), так и бэкенда (админки), соответствующие функции из данного файла будут выполнены.
Следовательно, с помощью файла functions.php вы можете решить целый спектр абсолютно разных задач:
- Наиболее простой вариант — изменение внешнего вида темы. Вспоминаются сразу хаки для ссылки читать далее где можно влиять на вид линка «read more» и формат анонса.
- Определение своих функций дабы позже вызывать их в других файлах шаблона, что экономит время на внедрение изменений на сайте (да, и вообще является нормальным принципом в программировании). Например, функция отображение первой картинки поста, которую после определения можно использовать в файлах темы для категорий, тегов, архивов.
- Настройка админки под себя — скрытие определенных пунктов из меню, изменение разных параметров отображения для других пользователей и т.п. Сразу вспоминается статья про скрытие custom fields для не админов. Также с помощью functions.php в WordPress можно создать специальную страницу настроек темы.
- Переопределение каких-то параметров системы — изменение размеров миниатюр для шаблона, а также разного рода хаки и фильтры. Например, с помощью данного файла можно подправить отображение комментариев в wp_list_comments.
Вообще файл functions.php в WordPress по логике и скорости работы напоминает плагины. Хотя при этом у них есть принципиальные отличия. Модули используются, как правило, для решения каких-то конкретных задач и применяются к любой теме вашего сайта. Плюс для работы их нужно активировать. Что касается файла шаблона functions.php, то он может содержать много разных функций и выполняется только для той темы, в которой определен. То есть при смене шаблона, все ваши текущие наработки будут отключены, а система начнет считывать информацию из другого файла функций (об этом следует помнить).
Где находится functions.php и как его редактировать?
Файл функций расположен в корневой директории темы (вместе с index.php, single.php и другими). То есть вы заходите в папку wp-content/themes/название_темы/, и он будет там. Это не то же самое что одноименный файл ядра, который находится в системной директории /wp-includes/, нужный нам объект — в папке шаблона.

Сейчас в WordPress файл шаблона functions.php можно найти в 99% популярных тем, но раньше он был не везде. Если в вашей теме нет functions.php, то вы спокойно можете его создать.
Есть два способа редактирования файла функций:
- через WP админку;
- с помощью текстового редактора.
Первый вариант достаточно простой и наглядный. Вы заходите в меню «Внешний вид» — «Редактор» и выбираете соответствующий файл для правки.

После внесения изменений нажмите кнопку «Обновить файл» в самом низу. Преимущество данного метода в том, что вам не нужно использовать какие-то дополнительные программы для работы, все происходит внутри панели администрирования. Однако не всегда это возможно сделать.
Если файл functions.php закрыт для записи, то воспользоваться встроенным редактором WordPress у вас не получится. В таком случае запускаете FTP клиент, например, Mozilla и скачиваете файл функций на локальный компьютер.

Для работы с php файлом советую использовать специальные бесплатные редакторы — Notepad++ или Sublime Text. При этом важно чтобы кодировка редактируемого файла была UTF-8 без BOM. Вот как можно ее выбрать в Notepad++:

Если этого не сделать, то из-за BOM может возникнуть глюк в WordPress. Для Sublime Text 2 в меню «File» есть опция «Reopen With Encoding», позволяющая открыть файл в нужной кодировке. Однако при запуске functions.php автоматически срабатывает UTF-8 (т.к. файл сохранен именно в ней), поэтому ничего дополнительно делать не нужно.
После внесения изменений в файл, загружаете его обратно на FTP в ту же самую корневую папку активного шаблона. Второй метод, как видите, чуть более сложный, но иногда без него не обойтись. Если вдруг, редактируя functions.php в WordPress админке вы допустили ошибку, то весь сайт может перестать работать (увидите белый экран). В таком случае исправить код можно будет лишь, скачав файл функций на локальный компьютер и отредактировав его в текстовом редакторе.
Вставка сниппетов (примеры кода и типичные ошибки)
Дабы у вас не возникало ошибок при работе с functions.php в WordPress, давайте рассмотрим основные правила вставки кода и возможные ошибки. Первым делом обратите внимание на глобальную структуру любого PHP файла:
<?php // . разный PHP код и функции . ?>
Здесь в начале идет специальный открывающий тег и в конце закрывающий. Важно чтобы не было никаких пробелов перед открывающимся и после закрывающегося тегов! Хотя в некоторых случаях вы можете встретить запись, когда последнего тега нет (для PHP это нормально). Давайте рассмотрим парочку примеров.
Ситуация 1
Допустим, вы нашли в интернете готовый сниппет для решения определенной задачи. И в описании сказано, что нужно вставить этот код в файл функций functions.php. В качестве примера выберем код удаления WP версии из wp_head:
Так размещать неправильно:
<?php // . разный PHP код и функции . <?php remove_action(‘wp_head’,’wp_generator’); ?> ?>
Возникает ошибка, поскольку система встречает тег открытия <?php нового PHP блока без закрытия предыдущего. Логичнее просто опустить <?php … ?> из найденного сниппета (так правильно):
<?php // . разный PHP код и функции . remove_action(‘wp_head’,’wp_generator’); ?>
Следующий вариант также будет работать (между PHP блоками не должно быть пробелов):
<?php // . разный PHP код и функции . ?><?php remove_action(‘wp_head’,’wp_generator’); ?>
Ситуация 2
Допустим вы хотите обновить jQuery в WordPress для чего нашли соответствующий код:
Неправильный вариант использования:
Нельзя размещать код после закрывающего PHP тега. Вам нужно поставить всю функцию внутрь конструкции:
Кстати, если в functions.php закрывающего тега ?> нет (что допускается), то добавляете нужный сниппет просто в конец файла.
Ситуация 3
Нельзя вставлять сниппет внутрь другой функции. Допустим, в файле шаблона functions.php у вас имеется следующий код:
Неправильный вариант вставки:
Добавить код можно только после закрывающего тега «>» первой функции. Вот так будет правильно:
Ситуация 4
Рассмотрим для ознакомления еще один вариант, когда внутри функции вы можете встретить конструкцию <?php … ?>, которая не будет нарушать общий порядок работы самого файла.
Тут нужно учитывать 2 нюанса. Во-первых, не должно быть ошибок в последовательности открывающих и закрывающих PHP тегов — каждый открытый блок должен быть закрыт. Во-вторых, внутри функции <…>пробелы и переносы строк между тегами <?php и ?> не критичны. В любом случае нужно быть очень внимательным в процессе редактирования. Плюс редакторов Notepad++ и Sublime Text в том, что они подсвечивают теги/функции, и так проще ориентироваться в коде.
Итого. Надеюсь, данное руководство по WordPress файлу functions.php вам пригодится. Данный инструмент в веб-разработке под WP весьма и весьма полезен. Нужно только внимательно с ним работать, так как ошибки могут привести к проблемам в работе сайта. Дабы ничего не нарушить я предпочитаю редактировать файл через текстовые редакторы, предварительно сохранив оригинальный вариант на всякий случай.
Если у вас остались вопросы по работе с functions.php в вордпресс, пишите их в комментариях.
P.S. Постовой. Продвижение и оптимизация сайта — важные знания для вебмастеров.
А вы знаете самые популярные сайты? — ТОП10 сайтов в мире (по посещаемости).
Понравился пост? Подпишись на обновления блога по
RSS,
Email или
twitter!
Оцените статью:
WooCommerce Theme Developer Handbook
WooCommerce looks great with all WordPress themes as of version 3.3, even if they are not WooCommerce-specific themes and do not formally declare support. Templates render inside the content, and this keeps everything looking natural on your site.
Non-WooCommerce themes, by default, also include:
- Zoom feature enabled – ability to zoom in/out on a product image
- Lightbox feature enabled – product gallery images pop up to examine closer
- Comments enabled, not Reviews – visitors/buyers can leave comments, same as a post, and not product ratings or reviews
If you want more control over the layout of WooCommerce elements or full reviews support your theme will need to integrate with WooCommerce. There are a few different ways you can do this, and they are outlined below.
Theme Integration
There are three possible ways to integrate WooCommerce with a theme. If you are using WooCommerce 3.2 or below you will need to use one of these methods to ensure WooCommerce shop and product pages are rendered correctly in your theme. If you are using a version of WooCommerce 3.3 or above you only need to do a theme integration if the automatic one doesn’t meet your needs.
Using woocommerce_content()
This solution allows you to create a new template page within your theme that is used for all WooCommerce taxonomy and post type displays. While an easy catch-all solution, it does have a drawback in that this template is used for all WC taxonomies (product categories, etc.) and post types (product archives, single product pages). Developers are encouraged to use the hooks instead.
To set up this template page:
1. Duplicate page.php
Duplicate your theme’s page.php file, and name it woocommerce.php. This file should be found like this: wp-content/themes/YOURTHEME/woocommerce.php .
2. Edit your page (woocommerce.php)
Open up your newly created woocommerce.php in a text editor, or the editor of your choice.
3. Replace the loop
Next you need to find the loop (see The_Loop). The loop usually starts with a:
and usually ends with:
This varies between themes. Once you have found it, delete it. In its place, put:
This will make it use WooCommerce’s loop instead. Save the file. You’re done.
Using hooks
The hook method is more involved, but it is also more flexible. This is similar to the method we use when creating themes. It’s also the method we use to integrate nicely with Twenty Ten to Twenty Sixteen themes.
Insert a few lines in your theme’s functions.php file.
First unhook the WooCommerce wrappers:
Then hook in your own functions to display the wrappers your theme requires:
Make sure that the markup matches that of your theme. If you’re unsure of which classes or IDs to use, take a look at your theme’s page.php for guidance.
Whenever possible use the hooks to add or remove content. This method is more robust than overriding the templates. If you have overridden a template, you have to update the template any time the file changes. If you are using the hooks, you will only have to update if the hooks change, which happens much less frequently.
Using template overrides
For information about overriding the WooCommerce templates with your own custom templates read the Template Structure section below. This method requires more maintenance than the hook-based method, as templates will need to be kept up-to-date with the WooCommerce core templates.
Declaring WooCommerce Support
If you are using custom WooCommerce template overrides in your theme you need to declare WooCommerce support using the add_theme_support function. WooCommerce template overrides are only enabled on themes that declare WooCommerce support. If you do not declare WooCommerce support in your theme, WooCommerce will assume the theme is not designed for WooCommerce compatibility and will use shortcode-based unsupported theme rendering to display the shop.
Declaring WooCommerce support is straightforward and involves adding one function in your theme’s functions.php file.
Basic Usage
Make sure you are using the after_setup_theme hook and not the init hook. Read more about this at the documentation for add_theme_support.
Usage with Settings
These are optional theme settings that you can set when declaring WooCommerce support.
thumbnail_image_width and single_image_width will set the image sizes for the shop. If these are not declared when adding theme support, the user can set image sizes in the Customizer under the WooCommerce > Product Images section.
The product_grid settings let theme developers set default, minimum, and maximum column and row settings for the Shop. Users can set the rows and columns in the Customizer under the WooCommerce > Product Catalog section.
Product gallery features (zoom, swipe, lightbox)
The product gallery introduced in 3.0.0 (read here for more information) uses Flexslider, Photoswipe, and the jQuery Zoom plugin to offer swiping, lightboxes and other neat features.
In versions 3.0 , 3.1 , and 3.2 , the new gallery is off by default and needs to be enabled using a snippet (below) or by using a compatible theme. This is because it’s common for themes to disable the WooCommerce gallery and replace it with their own scripts.
In versions 3.3 +, the gallery is off by default for WooCommerce compatible themes unless they declare support for it (below). 3rd party themes with no WooCommerce support will have the gallery enabled by default.
To enable the gallery in your theme, you can declare support like this:
You do not have to support all 3 parts of the gallery; you can pick and choose features. If a feature is not enabled, the scripts will not be loaded and the gallery code will not execute on product pages.
If gallery features are enabled (e.g. you have a theme which enabled them, or you are running a non-WC compatible theme), you can disable them with remove_theme_support :
You can disable any parts; you do not need to disable all features.
Template Structure
WooCommerce template files contain the markup and template structure for frontend and HTML emails of your store. If some structural change in HTML is necessary, you should override a template.
When you open these files, you will notice they all contain hooks that allow you to add/move content without needing to edit template files themselves. This method protects against upgrade issues, as the template files can be left completely untouched.
Template files can be found within the **/woocommerce/templates/** directory.
How to Edit Files
Edit files in an upgrade-safe way using overrides. Copy it into a directory within your theme named /woocommerce keeping the same file structure but removing the /templates/ subdirectory.
Example: To override the admin order notification, copy: wp-content/plugins/woocommerce/templates/emails/admin-new-order.php to wp-content/themes/yourtheme/woocommerce/emails/admin-new-order.php
The copied file will now override the WooCommerce default template file.
CSS Structure
Inside the assets/css/ directory, you will find the stylesheets responsible for the default WooCommerce layout styles.
Files to look for are woocommerce.scss and woocommerce.css .
- woocommerce.css is the minified stylesheet – it’s the CSS without any of the spaces, indents, etc. This makes the file very fast to load. This file is referenced by the plugin and declares all WooCommerce styles.
- woocommerce.scss is not directly used by the plugin, but by the team developing WooCommerce. We use SASS in this file to script the CSS in the first file easier and faster.
The CSS is written to make the default layout compatible with as many themes as possible by using % widths for all layout styles. It is, however, likely that you’ll want to make your own adjustments.
Modifications
To avoid upgrade issues, we advise not editing these files but rather use them as a point of reference.
If you just want to make changes, we recommend adding some overriding styles to your theme stylesheet. For example, add the following to your theme stylesheet to make WooCommerce buttons black instead of the default color:
WooCommerce also outputs the theme name (plus other useful information, such as which type of page is being viewed) as a class on the body tag, which can be useful for overriding styles.
Disabling WooCommerce styles
If you plan to make major changes, or create a theme from scratch, then you may prefer your theme not reference the WooCommerce stylesheet at all. You can tell WooCommerce to not use the default woocommerce.css .
Add the following code to your theme’s functions.php file:
With this definition in place, your theme will no longer use the WooCommerce stylesheet and give you a blank canvas upon which you can build your own desired layout/style.
Styling a WooCommerce theme from scratch for the first time is no easy task. There are many different pages and elements that need to be styled, and if you’re new to WooCommerce, you are probably not familiar with many of them. A non-exhaustive list of WooCommerce elements to style can be found here.
Examples
Storefront is the official WooCommerce theme built to the same exact standards as WooCommerce itself. The code is available on GitHub.
How to edit WooCommerce shop page programmatically (CSS and PHP)
Looking for ways to customize your shop page? In this tutorial, we’ll show you how to edit the WooCommerce shop page programmatically using both PHP and CSS.
In any online store, it is crucial to edit and optimize the shop page to increase your conversion rates. The shop page is where you display your products and it can make or break your business. If you’re running a WooCommerce store, we highly recommend you customize the shop page and make the most of it. In this guide, we’ll show you how to edit the WooCommerce shop page programmatically.
Why is it important to edit the shop page in WooCommerce?
The shop page is one of the most important pages in WooCommerce. It’s where you display your products to your visitors so it can have a huge effect on your store’s performance. A good shop page can improve user experience, increase conversion rates, and help you generate user engagement. A bad shop page, on the other hand, can do the exact opposite and stifle your business.
That’s why you must optimize it to maximize your sales. You can do that with plugins and page builders but if you have coding skills, creating your own solution is the way to go.
How to edit the WooCommerce shop page programmatically
We have previously seen different methods to customize the shop page. However, in this tutorial, we’ll focus on how to edit the WooCommerce shop page programmatically using a bit of CSS and PHP code. It’s worth noting that in this guide, we’ll work on a child theme and we will also edit the WooCommerce default shop template. We’ll put our focus on the WooCommerce template files and some references to the functions.php file of the child theme.
In this tutorial, you’ll learn how to edit the WooCommerce shop page programmatically to:
- Most popular products
- Best-selling products
- Top-rated
- Display products by taxonomies
- Customize WooCommerce shop page in functions.php
- Edit default columns count per row
- Apply CSS Style to the shop page
- Replace the default “sale” text for an animated gif
- Remove sorting options and pagination
Before you start
Please note that the following guide involves advanced coding so if you don’t have technical skills, we recommend you follow this other tutorial instead.
Before you start, we also recommend you install a child theme. You can check out our guide on how to create a child theme or use a plugin to do it in a few clicks. On top of that, as you’ll be changing core files, it’s a good idea to do a complete backup of your site.
So now, let’s see how to customize the shop page in WooCommerce with coding.
1. Disable the default WooCommerce shop page template
To customize the shop page, there are two possible approaches:
- You can overwrite the WooCommerce file responsible for printing the shop page
- Add customized scripts to the functions.php file of your child theme using WC hooks
You can edit the WooCommerce HTML template just like the functions.php file of the child theme, overwriting the core files to prevent deletion when there’s an update. However, as things don’t work exactly like in the functions.php file if WooCommerce decides to update these files, your customizations might not work anymore.
But this is nothing to worry about. WooCommerce is aware of this so they rarely update template files in a way that can break your scripts. The problem of working with the functions.php file is that the default WooCommerce shop page will still show up after you add your hooks.
So, first of all, you need to disable the default WooCommerce template shop page to create your template from scratch.
The archive-product.php file

In WooCommerce, the file responsible for the output on the shop page is called archive-product.php , and you can find it in the WooCommerce templates folder (WooCommerce > Templates > archive-product.php).
To overwrite this file, you need to copy and paste it in the WooCommerce folder in your child theme as shown below:
Now, let’s have a look at the archive-product.php file so you can see how WooCommerce displays the shop page. To do that, open your favorite integrated development environment (IDE), go to the templates folder of the WooCommerce plugin, and open the file. You can edit it and play around with it, the same way you can customize any other WC template file.
Before you do that, make sure you have a backup of the original file to undo any changes if necessary.
In the archive-product.php file, you will see several do_action() functions. These functions are used to create currently available WooCommerce hooks for the shop page. To completely disable the WooCommerce shop page, simply delete the loop responsible for printing the products:
You can make more changes here, but to simplify it, we’ll only delete the loop and leave everything else as it is. If you decide to make more changes, keep in mind that if you remove some of the do_action() functions, the corresponding shortcode will not work anymore on any page of the website.
After deleting the loop for printing products, the archive-product.php file will look like this:
That’s it! You have disabled the default shop page template and edited the WooCommerce shop page programmatically! Now you have an empty shop page so you can start designing your own.
2. Customize headers and content of WooCommerce shop page programmatically
The content and the headers can be any HTML markup that may include images, tables, or links. Or even something like an empty container to run an external JavaScript file. For this, you’ll need basic knowledge of WooCommerce shortcodes, since you are going to use them to display products on the shop page. If you’re not familiar with WC shortcodes, have a look at this guide.
Now, let’s edit the WC shop page and display products by most popular, best-selling, top-rated, and taxonomies. Additionally, we’ll show you how to add some headings and content outside the loop.
2.1 Display the most popular products
To display the most popular products you need to edit the archive-product.php file of your child theme. First, use the following shortcode
Right where the loop was before you deleted it. # display the most popular products: 2 products in 2 columns
In the shortcode, you will add a class called m-popular , which you can use later on when applying styles. In the above example, we set it to display 2 products in a single 2 columns row (columns=”2″ limit=”2″). Note that you can’t use shortcodes here in the same way you use them in a post or a page.

You must use the do_shortcode() function for the shortcodes to work. If everything went well, now you should see this on the shop page:
2.2 Best selling products
Another way to customize the WooCommerce shop programmatically is by sorting the products by best-sellers. For this, besides echoing the shortcode, you will add some content using a simple HTML markup (<h1>). Here, you can add any other type of content matching with proper HTML format.
Let’s display the best-selling products, this time in a layout of 2 rows and 3 columns. To do that, simply paste this right after the echo do_shortcode() line you’ve inserted in the previous step 2.1:

And what you get is this: If you only want to add Best sellers instead of the Most popular products, just replace the echo line in 2.1 with the one in 2.2.
2.3 Top rated products
Now, let’s play some more with shortcodes and display top-rated products. This time, we’ll use a shortcode without more attributes than a class.

Let’s see what happens after this: As you can see, the WooCommerce default layout has 4 columns. Let’s leave it like that for now, we’ll come back to it later.
2.4 Display products by taxonomies on the shop page
Apart from displaying best-selling or top-rated products, you can also display them by taxonomies. For example, the following code will print products for the Posters and Clothing categories, using the same attributes you used before but changing the number of columns to 5.
And this is how your archive-product.php should look now:
At this point, you should be able to understand how to use all the WooCommerce shortcodes and their attributes to build a custom shop page that can meet any design requirement.
2.5 Customize the WC shop page in functions.php
If you want to customize the WooCommerce shop page programmatically, you can also edit the functions.php file. For content outside the products loop, you can use some of the hooks seen in the archive-product.php file, running them from the functions.php file of the child theme. This way you make sure that your scripts will still work even if WC decides to update its templates files.
For this example, let’s add a custom header with a title, subtitle, description, and a banner. Paste this script in the functions.php file of the child theme:

This is how your shop page will look: In the same way, you can use the woocommerce_after_shop_loop hook to display some content at the end of the shop page.
3. Edit the number of products per row & apply a CSS stylesheet to the WC shop page
By now, you should be able to display products, sort them by featured, taxonomies, best-selling, and any other way that you want using WooCommerce shortcodes. On top of that, you should be able to insert any kind of content in any place you want on your shop page. But what if you could go even further and take your shop page to the next level? You can edit the template layout and add some CSS styles to programmatically customize your WooCommerce shop page even more.
3.1 Edit default columns count per row
If you specify the column attribute of the WC shortcode, you can set the number of products each row will display. Additionally, you can set the total number of products for the shortcode with the limit attribute:
However, if you don’t define the columns attribute, you can set the number of products that you want to print for each row using this script in the functions.php file of the child theme.
This will change the default number of products displayed per row only if there isn’t a column attribute in the WooCommerce shortcode.
3.2 Apply some CSS Styles to the shop page
To apply some CSS to the WooCommerce shop page, you can simply add your scripts in the template file like this:
This is ok for small pieces of CSS but it is not a recommended practice. To apply CSS Style the WordPress way, you need to use the wp_enqueue_scripts hook to load your scripts from a different file.
For this example, we are going to name this file shop_style.css and we’ll store it in our child theme main folder, at the same level of hierarchy as the default style.css file. After creating this file, paste the following script in your functions.php file:
As you can see, the if(is_shop()): conditional is required to be true to enqueue the shop_style.css file. In this file, you will have all the style scripts that you want to apply only to the shop page. This is different from the style.css file in the child theme that will apply the scripts to the entire website frontend. For this guide, we will use the following shop_style.css file but feel free to use your CSS scripts or change this one:
In the CSS file, you will find some selectors that contain custom classes. We’ve created them before creating the shortcodes. For example, we’ve added the “b-sellers” class in the shortcode like this:

So after adding the CSS Style to the WooCommerce shop page, you will get something like this (click the image to see it in full size):
Click on the image to view it in full size.
Also, keep in mind that we have the StoreFront theme active and, as you may know, the CSS selectors can be different on each website even if they have the same theme. So to make this file work, you might need to edit the selectors for your specific site.
BONUS: How to change the number of products per page
Now, let’s say you want to change the number of products you display per page on the shop page. If you want to display 10 products per page for example, simply add the following code to the functions.php file:
Where $cols contains the number of products per page that takes the value from Options -> Reading and returns the number of products you want to display on each page.
4. Edit the loop files of the WooCommerce shop page
So far, we’ve seen how to edit the archive-product.php template file to customize the WooCommerce shop page programmatically. This file is where the WC loop runs to display all the products of the page. Now, open the WooCommerce plugin folder in the plugin editor or your IDE, and open the loop folder. You will find it at the same level as the archive-product.php file.
In the loop folder, you will find some files that you can also edit to customize the shop page even more. To overwrite this file, you need to create a cloned folder and file in your child theme. Create a new folder called loop below your previously created WooCommerce folder.
After this, copy the original sale-flash.php file from the plugin templates and paste it inside this loop folder in your child theme.
We’ll use the sale-flash.php file to add an animated gif to all the products that are on sale. If you have a look at the file, you will see that this is the script responsible for displaying the “SALE” message when a product is on sale.
4.1 Replace default “sale” text for an animated gif
In this section, we’ll show you how to disable the default on-sale message and replace it with an animated gif. You need to edit the flash-sale.php file of your child theme so it looks like this:
There you can replace the gif file with any other gif that you like.
4.2 Remove sorting options and pagination
Now, let’s have a look at how to disable the “sort by” selector and the pagination functionality on the WooCommerce shop page. Similar to what you’ve done with the sale-flash.php file, you can achieve this by simply saving an empty file with the same name.
Create both files in the loop folder and call them orderby.php and pagination.php . To completely disable both files, you should only put this script in each of the files:

After doing this, you’ll have a cleaner header and footer on your shop page. On top of that, the pagination may not be very useful since you are displaying a large number of products. Note that in the sale-flash.php file, we’ve deleted the default WooCommerce behavior and added our own displaying an animated gif. This is a very basic task, but this technique offers a wide range of possibilities for advanced developers.
FINAL NOTES
- The WC template files of the child theme don’t prevent overwrites if WooCommerce decides to release an update of the templates. However, this rarely happens.
- These are sample scripts and must not be taken into production, they’re intended only for didactic purposes.
Bonus: Display Categories on the WooCommerce Shop Page
Finally, let’s see how you can add categories to the WooCommerce Shop Page using a bit of code. This method is recommended for users with coding skills. Apart from PHP, it’s recommended that you also know a bit of CSS to be able to style the code.
NOTE: Before starting, make sure you backup your site and create a child theme if you don’t have one already.
Add Categories to the Shop page
In your dashboard, go to Appearance > Theme Editor and open the child theme functions.php file. Click on the functions.php file on the right Theme Files sidebar and paste the following scripts to add your custom functions.
The below function will add your product categories before loading the other elements of your Shop page. This means that the shoppers will see all your product categories before the product catalog.
This function will add your Categories to the WooCommerce Shop page. However, keep in mind that they might not look exactly how you want, so you’ll have to style the new categories section with a bit of CSS. For more information about this, check out our post on how to display and style categories on the shop page.
Conclusion
All in all, the shop page is extremely important and can make or break your store. That’s why if you have coding skills, we recommend you edit the WooCommerce shop page programmatically and optimize it to increase your conversion rates.
In this guide, we’ve shown you how to add, remove, and customize different aspects of your store. However, these are just some examples and ideas that might help you find some inspiration and take your shop to the next level. Now it’s time for you to play around and develop your customizations.
For more guides to customize your WooCommerce store, we recommend you check out:
Finally, if you want to connect Facebook Shop with WooCommerce, you should have a look at this complete guide. Have you customized your online store? What have you changed? If you have any questions, leave a comment below and we’ll do our best to help you out! You can also check out the full code in Github.
How to Add WooCommerce Support to a Theme: 2 Ways of Doing It Right

If you’re using a WordPress theme that contains template overrides, you can’t use WooCommerce until you’ve declared support. Fortunately, this process is pretty straightforward and simply requires adding the add_theme_support function to accomplish.
Unless you take this quick step, WooCommerce will assume you’re using an incompatible theme. To help you avoid this mess, we’ll lay out the process from start to finish so you can add WooCommerce support and take advantage of its amazing functions in your theme.


Important! Make sure you use a child theme or custom theme before doing the changes.
Also, ensure that you have a reliable WordPress hosting service to keep your e-commerce website running smoothly. You can read more about hosting providers comparison.
What is the add_theme_support function?
This function is a pre-built hook within WordPress and is used by developers to add support for certain theme features. Nearly every theme uses the add_theme_support function, so it is important for any WordPress developer to be familiar with it.
This function can be used to accomplish a variety of things and is especially useful if you’re using or creating custom WordPress themes. In this article, we’ll explore how it can be used to add WooCommerce support to your theme.
In order to use the add_theme_support function, you will call upon it within the theme’s functions.php file. To use this function, you’ll generally need to use a command similar to this: add_theme_support( ‘feature’ ). Using the command to add WooCommerce support to your theme isn’t much different.
Add WooCommerce support to a theme using add_theme_support
Below, we’ll cover the steps you’ll need to take in order to add WooCommerce support to your theme:
1. Open Functions.php Editor:

First, you’ll need to navigate to your theme’s functions.php file. This can be done in more than one way.
- (not recommended) If you have access to the WordPress admin interface, the file can be edited from the Theme Editor. To do this, from the admin interface, go to the Appearance menu and click Editor. This will bring up a menu of your theme’s files, choose Themes Functions (functions.php) to bring up the editor.
- The safest way you can access your functions.php file is through an FTP tool. Simply open the tool and navigate to wp-content/themes/[name of your child or custom theme]. Within this folder, you should find the functions.php file.
2. Add Function to the .php file
Now you’re going to need to declare WooCommerce support within your functions.php file. You can do it by inputting the following:
After this, you should no longer receive the annoying “Your theme does not declare WooCommerce support” message.

3. Disable Default Styling for WooCommerce
If you wish to disable the default styling for WooCommerce, add the following text:
The class_exists(‘Woocommerce’) function is simply used to ensure that the WooCommerce plugin is installed and working correctly. After you’re certain it’s active, you can go ahead and disable its default styling.
4. Duplicate the page.php file
Locate your theme’s page.php file and make a copy of it. Name the new copy ‘woocommerce.php.’ Make sure this file is located in the following directory:
5. Edit woocommerce.php
Open the newly created woocommerce.php file in a text editor and look for the loop that usually starts with <?php if ( have_posts() ) : and most of the time ends with <?php endif; ?>. Keep in mind, the loop’s text may vary depending on the theme you’re using.
Once you find the correct loop you’re going to want to delete it. Replace it with the following text:
Doing this will make your new woocommerce.php template use the WooCommerce loop rather than the default. Using woocommerce_content() will allow you to load your product list on your site’s main page, product search page, product category page, and even when viewing a single product’s page.
6. Customize woocommerce.php
Now that woocommerce.php is added to your theme, you can customize it to fit your needs. There are also some optional theme settings that can be enabled when declaring WooCommerce support. In the next section, we’ll cover this in more detail.
Optional Settings When Adding WooCommerce Support
If you want to further customize your store, WooCommerce gives you some options. The following theme settings can be altered while you’re adding WooCommerce support:
Image Size
If you’d like to set the standard image size for your online shop, input the following when declaring WooCommerce support:
Product Grid

Another optional WooCommerce setting is the product grid. To set this up, input the following when declaring WooCommerce support:
Both Image Size and Product Grid
To set up both your image size and the product grid at the same time, add the following:
Image Zoom/Magnification
To add image zoom/magnification feature to your theme’s gallery, you can use add_theme_support and simply add:
Image Slider
If you’d like to add a slider to the images in your shop’s gallery, type:
Lightbox
A lightbox can also be added to your image gallery. To do this, simply copy the following text:
Zoom, Slider, and Lightbox
You can also add all three; image magnification, a slider, and lightbox, all at once with one simple command:
You can omit whichever feature you’d like as well. For example, if you’d like the lightbox and the zoom but could do without the slider, then simply keep add_theme_support( ‘wc-product-gallery-zoom’ ) and add_theme_support( ‘wc-product-gallery-lightbox’ ) but leave out add_theme_support( ‘wc-product-gallery-slider’ );.
WooCommerce Shortcodes
Shortcodes are macros that you can use to post dynamic content to your page. To use a shortcode, you will input a small bit of text in between two brackets, like so [example]. Shortcodes are rather easy to use, and they don’t require any advanced programming knowledge to take advantage of.
How to Use WooCommerce Shortcodes
Using shortcodes in the WordPress block editor is incredibly easy. The following steps will guide you through this process:
- Navigate to the page you’d like to edit in WordPress’s block editor.
- On the top left-hand side of the screen you will see a ‘+’ button. Click it.
- This will open a new menu with a text box containing ‘Search for a block.” In this box, type ‘shortcode’ and press the Enter key.
- Click the ‘Shortcodes’ widget that comes up, and input the shortcode that you would like to use.

Popular Shortcodes You Can Use With WooCommerce
WooCommerce offers loads of useful shortcodes. Below, I’ll list some of the more popular ones to help get you started. But remember, this list is far from comprehensive, so if you’re looking for something and you can’t find it on this list that doesn’t mean it’s not available.
These three shortcodes are very important to include on your site in order for WooCommerce to function properly:
While these shortcodes may not be necessary in order for WooCommerce to function properly, you may still find them to be useful on your page:
As an alternative, you can try WooCommerce Blocks instead of the Shortcode Gutenberg element.
Support added – what next?
Online stores are no small feat – even with WooCommerce. You may need some additional info about WooCommerce blocks available for you in WordPress. Also, if you want your site to stand out from the crowd (which you probably do when you sell things), you’d like to have it all customized. Therefore, make sure you know how to customize WooCommerce. Decide on the specifics, make it all convenient for the clients, and set up the necessary payment methods.
It may be a tad too complicated if you haven’t had a chance to deal with e-commerce sites on the backend before. If that’s the case, we can help you with building the best online store. Just tell us about your project, and we’ll get back to you with the best offer.
Now you’re ready to build the online store of your dreams using WordPress with the support of WooCommerce. Not only can you take advantage of this powerful tool to market your products, but you also have a head start with some great customization options. So what are you waiting for? Add WooCommerce support and upgrade your site today. If you need any support, we’re happy to assist you.
If you’re not confident about handling the technical aspects of adding WooCommerce support to your theme, or if you simply don’t have the time, consider hiring professionals to do it for you. Many top-rated agencies and freelancers specialize in WooCommerce integration and can ensure a smooth transition to a fully functional online store. In this section, we’ll provide you with a curated list of the best agencies offering these services, along with reliable freelance platforms where you can find qualified individuals. Let the experts handle the complexities while you focus on growing your business.
Best WooCommerce Experts for your project
We specialize in WooCommerce development to help you create a powerful, customized, and profitable online store. Our team of experienced developers, designers, and digital marketers are dedicated to providing you with top-notch WooCommerce solutions that cater to your unique business needs.
We convert websites from Figma to WordPress, manually controlling each stage. Unlike automated options, Figma2WP conversions come with no code bloats or unnecessary load.
We work with Figma and WordPress since 2015. We are a team of super-skilled digital experts, recognized around the world. We offer WordPress development & maintenance, web design, and branding.
We value ethical web development – and we practice what we preach.
We’re a WordPress agency that specializes in all kinds of WordPress services, from WordPress development to custom web design to WordPress migration to WordPress white-label; we do it all. Seahawk is trusted by top web hosts such as GoDaddy, DreamHost, Convesio, Alibaba Cloud, and agencies for WordPress services. We also offer WooCommerce development services to help eCommerce businesses take new heights.
WPRiders provides WooCommerce development for small to mid-sized businesses and startups. Their monthly development plans start at $850/month and give you access to a multidisciplinary team of resources, outsourced CTO, custom feature development, and ongoing website support. The team is all about building and growing WooCommerce websites, digital products, online platforms, and custom plugins to help you keep up with the latest trends in web technology.