@ -1,412 +1,31 @@
<?php
<?php
require_once __DIR__ . '/vendor/autoload.php'; // для работы Composer пакетов (библиотек)
// require once вместо include использовать!
// доделать example module и component
require_once __DIR__ . '/vendor/autoload.php';
// Initialize Timber.
// Initialize Timber.
Timber\Timber::init();
Timber\Timber::init();
Timber::$dirname = [
[
'modules',
'templates'
],
];
use Timber\PostCollection;
use Timber\Integrations\WooCommerce\Product as TimberProduct;
add_filter( 'timber/integrations', function ( array $integrations ): array {
$integrations[] = new \Timber\Integrations\WooCommerce\WooCommerceIntegration();
return $integrations;
} );
// function theme_enqueue_scripts() {
/* Подключение файлов с разной бизнес-логикой */
// // Swiper
// function require_all_temp_functions() {
// wp_enqueue_script( 'gp-front-page-materialize', get_template_directory_uri() . '/modules/layout/assets/js/materialize.min.js', array(), null, true );
// foreach (glob(__DIR__ . '/temp-functions/*.php') as $file) {
// require_once $file;
// }
// }
// }
// add_action('wp_enqueue_scripts', 'theme_enqueue_scripts');
// require_all_temp_functions();
add_action('timber/init', function() {
// Инициализируем WooCommerce интеграцию
if (class_exists('Timber\Integrations\WooCommerce\WooCommerce')) {
Timber\Integrations\WooCommerce\WooCommerce::init();
}
});
function theme_add_woocommerce_support()
{
add_theme_support('woocommerce');
}
add_action('after_setup_theme', 'theme_add_woocommerce_support');
add_theme_support('post-thumbnails');
add_action('after_setup_theme', function() {
add_theme_support('comments');
update_option('default_comment_status', 'open');
});
//Подруключение всех ajax controller если запрос сделан по ajax
$modulesDir = __DIR__ . '/modules';
// Функция для рекурсивного подключения файлов
function requireAjaxControllers($baseDir) {
$modules = glob($baseDir . '/*', GLOB_ONLYDIR);
foreach ($modules as $module) {
$moduleController = $module . '/module-ajax-controller.php';
if (file_exists($moduleController)) {
require_once $moduleController;
}
$componentsDir = $module . '/components';
if (is_dir($componentsDir)) {
$components = glob($componentsDir . '/*', GLOB_ONLYDIR);
foreach ($components as $component) {
$componentController = $component . '/component-ajax-controller.php';
if (file_exists($componentController)) {
require_once $componentController;
}
}
}
}
}
function requireShortcodes($baseDir) {
$modules = glob($baseDir . '/*', GLOB_ONLYDIR);
foreach ($modules as $module) {
$componentsDir = $module . '/shortcodes';
if (is_dir($componentsDir)) {
// Рекурсивно подключаем все shortcodes.php
requireShortcodesRecursive($componentsDir);
}
}
}
function requireShortcodesRecursive($dir) {
// Получаем все подпапки в текущем каталоге
$components = glob($dir . '/*', GLOB_ONLYDIR);
foreach ($components as $component) {
// Проверяем наличие файла shortcode.php в текущей подпапке
$componentController = $component . '/shortcode.php';
if (file_exists($componentController)) {
require_once $componentController;
}
// Рекурсивно вызываем функцию для каждой найденной подпапки
requireShortcodesRecursive($component);
}
}
// Пример вызова функции
function includeFilesFromFolder($folder) {
// Проверяем, существует ли папка
if (is_dir($folder)) {
// Открываем директорию
$files = scandir($folder);
// Перебираем файлы в директории
foreach ($files as $file) {
// Пропускаем текущую и родительскую директории
if ($file !== '.' & & $file !== '..') {
// Формируем полный путь к файлу
$filePath = $folder . DIRECTORY_SEPARATOR . $file;
// Проверяем, является ли это файлом и имеет ли нужное расширение (например, .php)
if (is_file($filePath) & & pathinfo($filePath, PATHINFO_EXTENSION) === 'php') {
include_once $filePath; // Подключаем файл
}
}
}
} else {
throw new Exception("Директория не найдена: $folder");
}
}
// Подключает модуль из папки /modules/
function include_module($module_name) {
// Убедитесь, что имя модуля не пустое
if (empty($module_name)) {
return;
}
// Получаем путь к каталогу модуля
$module_dir = get_template_directory() . '/modules/' . $module_name;
// Регистрируем стили и скрипты
add_action('wp_enqueue_scripts', function() use ($module_name, $module_dir) {
// Подключаем стили
$css_dir = $module_dir . '/assets/css';
if (is_dir($css_dir)) {
$css_files = scandir($css_dir);
// Приоритетные файлы
$priority_files = [
'normalize.css',
'gp-style-core.css',
'gp-style-desktop.css',
'gp-style-tablet.css',
'gp-style-mobile.css'
];
// Подключаем приоритетные файлы в заданном порядке
foreach ($priority_files as $priority_file) {
$file_path = $css_dir . '/' . $priority_file;
if (file_exists($file_path)) {
wp_enqueue_style(
$module_name . '-' . pathinfo($priority_file, PATHINFO_FILENAME),
get_template_directory_uri() . '/modules/' . $module_name . '/assets/css/' . $priority_file,
[],
filemtime($file_path)
);
}
}
// Подключаем остальные CSS-файлы
foreach ($css_files as $css_file) {
if (
pathinfo($css_file, PATHINFO_EXTENSION) === 'css' & &
$css_file !== '.' & &
$css_file !== '..' & &
!in_array($css_file, $priority_files)
) {
$file_path = $css_dir . '/' . $css_file;
wp_enqueue_style(
$module_name . '-' . pathinfo($css_file, PATHINFO_FILENAME),
get_template_directory_uri() . '/modules/' . $module_name . '/assets/css/' . $css_file,
[],
filemtime($file_path)
);
}
}
}
// Подключаем скрипты
// require once вместо include использовать!
$js_dir = $module_dir . '/assets/js';
require_once __DIR__ . '/temp-functions/cart-logic.php';
if (is_dir($js_dir)) {
require_once __DIR__ . '/temp-functions/timber-logic.php';
$js_files = scandir($js_dir);
require_once __DIR__ . '/temp-functions/woocommerce-logic.php';
foreach ($js_files as $js_file) {
require_once __DIR__ . '/temp-functions/modules-logic.php';
if (
require_once __DIR__ . '/temp-functions/ajax-logic.php';
pathinfo($js_file, PATHINFO_EXTENSION) === 'js' & &
require_once __DIR__ . '/temp-functions/shortcodes-logic.php';
$js_file !== '.' & &
$js_file !== '..'
) {
$file_path = $js_dir . '/' . $js_file;
wp_enqueue_script(
$module_name . '-' . pathinfo($js_file, PATHINFO_FILENAME),
get_template_directory_uri() . '/modules/' . $module_name . '/assets/js/' . $js_file,
['jquery'],
filemtime($file_path),
true
);
}
}
}
});
// Подключаем контроллер модуля
$module_controller = $module_dir . '/module-controller.php';
if (file_exists($module_controller)) {
include_once $module_controller ;
}
}
function include_component($module_name, $component_name) {
// Убедитесь, что имя модуля и компонента не пустые
if (empty($module_name) || empty($component_name)) {
return;
}
// Получаем путь к каталогу модуля
$component_dir = get_template_directory() . '/modules/' . $module_name . '/components/' . $component_name;
// Регистрируем стили и скрипты
add_action('wp_enqueue_scripts', function() use ($module_name, $component_name, $component_dir) {
// Подключаем стили
$css_dir = $component_dir . '/assets/css';
if (is_dir($css_dir)) {
$css_files = scandir($css_dir);
// Приоритетные файлы в нужном порядке
$priority_files = [
'gp-style-core.css',
'gp-style-desktop.css',
'gp-style-tablet.css',
'gp-style-mobile.css'
];
// Подключаем приоритетные файлы в заданном порядке
foreach ($priority_files as $priority_file) {
$file_path = $css_dir . '/' . $priority_file;
if (file_exists($file_path)) {
$handle = "{$module_name}-{$component_name}-" . pathinfo($priority_file, PATHINFO_FILENAME);
$src = get_template_directory_uri() . "/modules/{$module_name}/components/{$component_name}/assets/css/{$priority_file}";
wp_enqueue_style($handle, $src, [], filemtime($file_path)); // Используем filemtime для версии
}
}
// Подключаем остальные CSS-файлы
foreach ($css_files as $css_file) {
if (pathinfo($css_file, PATHINFO_EXTENSION) === 'css' & & !in_array($css_file, $priority_files)) {
$file_path = $css_dir . '/' . $css_file;
$handle = "{$module_name}-{$component_name}-" . pathinfo($css_file, PATHINFO_FILENAME);
$src = get_template_directory_uri() . "/modules/{$module_name}/components/{$component_name}/assets/css/{$css_file}";
wp_enqueue_style($handle, $src, [], filemtime($file_path));
}
}
}
// Подключаем скрипты
$js_dir = $component_dir . '/assets/js';
if (is_dir($js_dir)) {
$js_files = scandir($js_dir);
foreach ($js_files as $js_file) {
if (pathinfo($js_file, PATHINFO_EXTENSION) === 'js') {
$file_path = $js_dir . '/' . $js_file;
$handle = "{$module_name}-{$component_name}-" . pathinfo($js_file, PATHINFO_FILENAME);
$src = get_template_directory_uri() . "/modules/{$module_name}/components/{$component_name}/assets/js/{$js_file}";
wp_enqueue_script($handle, $src, ['jquery'], filemtime($file_path), true);
}
}
}
});
$component_controller = $component_dir . '/component-controller.php';
if (file_exists($component_controller)) {
include_once $component_controller ;
}
}
/**
* Регистрируем шаблоны из всех подпапок /templates/
*/
add_filter('theme_page_templates', function ($templates) {
// Путь к папке с шаблонами
$custom_templates_dir = get_template_directory() . '/templates/';
// Ищем ВСЕ PHP-файлы в /templates/ и подпапках
$all_templates = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($custom_templates_dir)
);
foreach ($all_templates as $template_file) {
// Пропускаем не-PHP файлы и папки
if ($template_file->isDir() || $template_file->getExtension() !== 'php') {
continue;
}
// Получаем относительный путь (например, "pages/template-landing.php")
$relative_path = str_replace($custom_templates_dir, '', $template_file->getPathname());
// Формируем имя шаблона (убираем .php и заменяем слэши на дефисы)
$template_name = str_replace(['/', '.php'], [' - ', ''], $relative_path);
// Добавляем в список шаблонов
$templates['templates/' . $relative_path] = $template_name;
}
return $templates;
});
/* Подключаем все файлы с глобальными функциями */
includeFilesFromFolder(get_template_directory() . '/global-functions');
// Add the function to the Timber context
add_filter('timber/context', function($context) {
$context['template_path'] = get_template_directory_uri();
$current_url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$context['current_url'] = htmlspecialchars($current_url);
return $context;
});
/**
* Подключает статические CSS и JS файлы из указанной директории
*
* @param string $dir_name Название директории в папке /static/
* @param array $options Дополнительные параметры:
* - 'css' => false - отключить подключение CSS
* - 'js' => false - отключить подключение JS
* - 'version' => string - версия файлов (по умолчанию использует время модификации файла)
*/
function enqueue_static_assets($dir_name, $options = []) {
// Устанавливаем пути к директориям
$static_dir = get_template_directory() . '/static/' . $dir_name;
$static_uri = get_template_directory_uri() . '/static/' . $dir_name;
// Подключаем CSS файлы
if (!isset($options['css']) || $options['css'] !== false) {
$css_dir = $static_dir . '/css/';
if (file_exists($css_dir)) {
$css_files = scandir($css_dir);
foreach ($css_files as $file) {
if (pathinfo($file, PATHINFO_EXTENSION) === 'css') {
$handle = $dir_name . '-' . pathinfo($file, PATHINFO_FILENAME);
$src = $static_uri . '/css/' . $file;
$ver = isset($options['version']) ? $options['version'] : filemtime($css_dir . $file);
wp_enqueue_style(
$handle,
$src,
array(),
$ver
);
}
}
}
}
// Подключаем JS файлы
if (!isset($options['js']) || $options['js'] !== false) {
$js_dir = $static_dir . '/js/';
if (file_exists($js_dir)) {
$js_files = scandir($js_dir);
foreach ($js_files as $file) {
if (pathinfo($file, PATHINFO_EXTENSION) === 'js') {
$handle = $dir_name . '-' . pathinfo($file, PATHINFO_FILENAME);
$src = $static_uri . '/js/' . $file;
$ver = isset($options['version']) ? $options['version'] : filemtime($js_dir . $file);
$in_footer = strpos($file, 'admin') === 0 ? false : true;
wp_enqueue_script(
$handle,
$src,
array(),
$ver,
$in_footer
);
}
}
}
}
}
add_action('init', function() {
add_action('init', function() {
if (function_exists('wpseo_load_textdomain')) {
if (function_exists('wpseo_load_textdomain')) {
@ -415,26 +34,25 @@ add_action('init', function() {
if (function_exists('pll_load_textdomain')) {
if (function_exists('pll_load_textdomain')) {
pll_load_textdomain();
pll_load_textdomain();
}
}
add_filter('timber/context', function($context) {
$context['current_lang'] = pll_current_language();
return $context;
});
}, 1);
}, 1);
/* Вставить в поиск по модулям */
$modules_path = get_template_directory() . '/modules/*/editor-blocks/*/editor-block-controller.php';
$modules_path = get_template_directory() . '/modules/*/editor-blocks/*/editor-block-controller.php';
foreach (glob($modules_path) as $file) {
foreach (glob($modules_path) as $file) {
require_once $file; // Подключаем каждый найденный файл
require_once $file; // Подключаем каждый найденный файл
}
}
requireShortcodes(get_template_directory() . '/modules');
// include_module('blog');
require_once('modules/blog/module-ajax-controller.php'); // !!! внутри него include_module('blog');
require_once('modules/blog/module-ajax-controller.php');
require_once('modules/forms/module-ajax-controller.php');
require_once('modules/forms/module-ajax-controller.php');
require_once('modules/shop/module-ajax-controller.php');
require_once('modules/shop/module-ajax-controller.php');
require_once('modules/profile/module-ajax-controller.php');
require_once('modules/profile/module-ajax-controller.php');
require_once('modules/footer/module-ajax-controller.php');
require_once('modules/footer/module-ajax-controller.php');
require_once('modules/author/module-ajax-controller.php');
add_action('wp', 'my_custom_checkout_code');
add_action('wp', 'my_custom_checkout_code');
function my_custom_checkout_code() {
function my_custom_checkout_code() {
@ -443,11 +61,16 @@ function my_custom_checkout_code() {
}
}
}
}
require_once('modules/author/module-ajax-controller.php');
include_module('forms');
include_module('forms');
include_module('layout');
include_module('layout');
// include_module('forms');
// include_module('shop');
// include_module('profile');
// include_module('footer');
// include_module('author');
// include_module('layout');
class WooProduct extends Timber\Post {
class WooProduct extends Timber\Post {
protected $wc_product;
protected $wc_product;