You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
381 lines
13 KiB
381 lines
13 KiB
<?
|
|
|
|
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 подгрузка товаров в архиве
|
|
add_action( 'wp_ajax_nopriv_get_products', 'get_products' );
|
|
add_action( 'wp_ajax_get_products', 'get_products' );
|
|
|
|
function get_products() {
|
|
global $post;
|
|
|
|
if (function_exists('WC')) {
|
|
WC();
|
|
}
|
|
|
|
// Потом Timber
|
|
|
|
$context = Timber::context();
|
|
$context['get_page'] = empty($_POST['get_page']) ? 1 : $_POST['get_page'];
|
|
$context['criteria_for_new_product'] = date('Y-m-d', strtotime('-30 days'));
|
|
$context['get_category'] = isset($_POST['get_category']) ? $_POST['get_category'] : NULL;
|
|
$context['get_category_type'] = isset($_POST['get_category_type']) ? $_POST['get_category_type'] : NULL;
|
|
|
|
// Задаем количество постов для подзагрузки Ajax
|
|
$posts_per_page = 12;
|
|
|
|
$args = array(
|
|
'post_type' => 'product',
|
|
'post_status' => 'publish',
|
|
'posts_per_page' => $posts_per_page,
|
|
'paged' => $context['get_page'],
|
|
'has_password' => FALSE
|
|
);
|
|
|
|
$count_args = array(
|
|
'post_type' => 'product',
|
|
'post_status' => 'publish',
|
|
'posts_per_page' => -1,
|
|
'has_password' => FALSE
|
|
);
|
|
|
|
if ($context['get_category'] != NULL) {
|
|
$categories = [
|
|
'tax_query' => array(
|
|
array(
|
|
'taxonomy' => $context['get_category_type'],
|
|
'field' => 'term_id',
|
|
'terms' => array($context['get_category']),
|
|
'operator' => 'IN'
|
|
),
|
|
array(
|
|
'taxonomy' => 'product_visibility',
|
|
'field' => 'slug',
|
|
'terms' => 'exclude-from-catalog',
|
|
'operator' => 'NOT IN'
|
|
)
|
|
)
|
|
];
|
|
$args = array_merge($args, $categories);
|
|
$count_args = array_merge($count_args, $categories);
|
|
}
|
|
|
|
$products = new WP_Query($args);
|
|
$products = new Timber\PostQuery($products, 'Timber\Integrations\WooCommerce\Product');
|
|
|
|
$context['posts'] = $products;
|
|
|
|
$context['count'] = count(Timber::get_posts($count_args));
|
|
|
|
if ($context['count'] <= $context['get_page'] * $posts_per_page) {
|
|
$context['ended'] = true;
|
|
}
|
|
|
|
Timber::render( '_blocks/shop/archive-product-ajaxload.twig', $context );
|
|
|
|
die();
|
|
}
|
|
|
|
|
|
//Получить аттрибуты товара по ID
|
|
function get_product_info ($id, $type) {
|
|
if (!$id) {
|
|
return '';
|
|
}
|
|
$product = wc_get_product($id);
|
|
if (!$product) {
|
|
return '';
|
|
}
|
|
if ($type == 'price') {
|
|
return $product->get_price();
|
|
} elseif ($type == 'weight') {
|
|
return $product->get_weight() ? $product->get_weight() . ' кг' : '';
|
|
}
|
|
return '';
|
|
}
|
|
|
|
//Кнопка добавления в корзину
|
|
function get_add_to_cart_button ($id) {
|
|
$product = wc_get_product( $id );
|
|
return '<a href="'. $product->add_to_cart_url(). '" value="'. esc_attr( $product->get_id() ) .'"
|
|
class="ajax_add_to_cart add_to_cart_button button button--gradient button--base button--100-perc" data-product_id="'. $id .'">'. pll__('Добавить в корзину') .'</a>';
|
|
}
|
|
|
|
//Получить товары из одной подборки по весу
|
|
function get_collection_siblings ($term) {
|
|
if (!$term) {
|
|
return [];
|
|
}
|
|
|
|
$args = array(
|
|
'posts_per_page' => -1,
|
|
'post_type' => 'product',
|
|
'order' => 'ASC',
|
|
'order_by' => 'name',
|
|
'tax_query' => [
|
|
[
|
|
'taxonomy' => 'pa_collection',
|
|
'terms' => $term,
|
|
'field' => 'id',
|
|
]
|
|
],
|
|
);
|
|
|
|
$siblings = get_posts($args);
|
|
|
|
$sibl_arr = [];
|
|
|
|
foreach( $siblings as $sibling ) {
|
|
$sibl_arr [] = $sibling;
|
|
}
|
|
|
|
return $sibl_arr;
|
|
}
|
|
|
|
add_filter( 'woocommerce_price_trim_zeros', '__return_true' );
|
|
|
|
add_filter('woocommerce_product_data_tabs', function($tabs) {
|
|
$tabs['composition_tab'] = array(
|
|
'label' => 'Состав',
|
|
'target' => 'composition_product_data',
|
|
'class' => array('composition_tab'),
|
|
'priority' => 60,
|
|
);
|
|
$tabs['feeding_tab'] = array(
|
|
'label' => 'Рекомендации по кормлению',
|
|
'target' => 'feeding_product_data',
|
|
'class' => array('feeding_tab'),
|
|
'priority' => 61,
|
|
);
|
|
$tabs['important_tab'] = array(
|
|
'label' => 'Важно',
|
|
'target' => 'important_product_data',
|
|
'class' => array('important_tab'),
|
|
'priority' => 62,
|
|
);
|
|
return $tabs;
|
|
});
|
|
|
|
|
|
add_action('woocommerce_product_data_panels', function() {
|
|
global $post;
|
|
$composition = get_post_meta($post->ID, '_composition', true);
|
|
echo '<div id="composition_product_data" class="panel woocommerce_options_panel">';
|
|
woocommerce_wp_textarea_input([
|
|
'id' => '_composition',
|
|
'label' => 'Состав',
|
|
'desc_tip' => true,
|
|
'description' => 'Введите состав товара',
|
|
'value' => $composition
|
|
]);
|
|
echo '</div>';
|
|
});
|
|
|
|
|
|
add_action('woocommerce_product_data_panels', function() {
|
|
global $post;
|
|
$feeding = get_post_meta($post->ID, '_feeding_recommendations', true);
|
|
echo '<div id="feeding_product_data" class="panel woocommerce_options_panel">';
|
|
woocommerce_wp_textarea_input([
|
|
'id' => '_feeding_recommendations',
|
|
'label' => 'Рекомендации по кормлению',
|
|
'desc_tip' => true,
|
|
'description' => 'Введите рекомендации по кормлению',
|
|
'value' => $feeding
|
|
]);
|
|
echo '</div>';
|
|
});
|
|
|
|
|
|
add_action('woocommerce_product_data_panels', function() {
|
|
global $post;
|
|
$important = get_post_meta($post->ID, '_important', true);
|
|
echo '<div id="important_product_data" class="panel woocommerce_options_panel">';
|
|
woocommerce_wp_textarea_input([
|
|
'id' => '_important',
|
|
'label' => 'Важно',
|
|
'desc_tip' => true,
|
|
'description' => 'Введите важную информацию',
|
|
'value' => $important
|
|
]);
|
|
echo '</div>';
|
|
});
|
|
|
|
add_action('woocommerce_process_product_meta', function($post_id) {
|
|
if (isset($_POST['_composition'])) {
|
|
update_post_meta($post_id, '_composition', sanitize_textarea_field($_POST['_composition']));
|
|
}
|
|
if (isset($_POST['_feeding_recommendations'])) {
|
|
update_post_meta($post_id, '_feeding_recommendations', sanitize_textarea_field($_POST['_feeding_recommendations']));
|
|
}
|
|
if (isset($_POST['_important'])) {
|
|
update_post_meta($post_id, '_important', sanitize_textarea_field($_POST['_important']));
|
|
}
|
|
});
|
|
// Добавление поля для выбора рекомендуемых товаров
|
|
function register_recommended_products_acf_field() {
|
|
if (function_exists('acf_add_local_field_group')) {
|
|
acf_add_local_field_group(array(
|
|
'key' => 'group_recommended_products',
|
|
'title' => 'Рекомендуемые товары',
|
|
'fields' => array(
|
|
array(
|
|
'key' => 'field_recommended_products',
|
|
'label' => 'Выберите рекомендуемые товары',
|
|
'name' => 'recommended_products',
|
|
'type' => 'relationship',
|
|
'instructions' => 'Выберите товары, которые будут отображаться в секции "вашему питомцу может понравиться"',
|
|
'required' => 0,
|
|
'conditional_logic' => 0,
|
|
'post_type' => array(
|
|
0 => 'product',
|
|
),
|
|
'filters' => array(
|
|
0 => 'search',
|
|
1 => 'taxonomy',
|
|
),
|
|
'return_format' => 'object',
|
|
'min' => '',
|
|
'max' => 8,
|
|
),
|
|
),
|
|
'location' => array(
|
|
array(
|
|
array(
|
|
'param' => 'post_type',
|
|
'operator' => '==',
|
|
'value' => 'product',
|
|
),
|
|
),
|
|
),
|
|
'menu_order' => 0,
|
|
'position' => 'normal',
|
|
'style' => 'default',
|
|
'label_placement' => 'top',
|
|
'instruction_placement' => 'label',
|
|
'hide_on_screen' => '',
|
|
));
|
|
}
|
|
}
|
|
add_action('acf/init', 'register_recommended_products_acf_field');
|
|
|
|
add_action('wp_footer', 'remove_view_cart_button_js');
|
|
function remove_view_cart_button_js() {
|
|
?>
|
|
<script>
|
|
jQuery(document).ready(function($) {
|
|
$(document).on('added_to_cart', function() {
|
|
$('.added_to_cart.wc-forward').remove();
|
|
});
|
|
});
|
|
</script>
|
|
<?php
|
|
}
|
|
|
|
|
|
function custom_remove_woocommerce_styles_on_checkout( $enqueue_styles ) {
|
|
if ( is_checkout() ) {
|
|
return []; // Удаляет все стандартные стили WooCommerce только на странице checkout
|
|
}
|
|
|
|
return $enqueue_styles;
|
|
}
|
|
add_filter( 'woocommerce_enqueue_styles', 'custom_remove_woocommerce_styles_on_checkout' );
|
|
|
|
|
|
|
|
// Перехватываем валидацию и заменяем поведение
|
|
add_filter('woocommerce_add_to_cart_validation', 'custom_limit_stock_add_to_cart_behavior', 10, 5);
|
|
function custom_limit_stock_add_to_cart_behavior($passed, $product_id, $quantity, $variation_id = 0, $variations = []) {
|
|
$product = wc_get_product($variation_id ?: $product_id);
|
|
|
|
if (!$passed || !$product || !$product->managing_stock()) {
|
|
return $passed;
|
|
}
|
|
|
|
$stock = $product->get_stock_quantity();
|
|
$in_cart = WC()->cart->get_cart_item_quantities();
|
|
$already_in_cart = $in_cart[$product->get_id()] ?? 0;
|
|
|
|
$total = $already_in_cart + $quantity;
|
|
|
|
if ($total > $stock) {
|
|
$can_add = max($stock - $already_in_cart, 0);
|
|
|
|
if ($can_add > 0) {
|
|
// Добавим максимум
|
|
WC()->cart->add_to_cart($product_id, $can_add, $variation_id, $variations);
|
|
|
|
wc_add_notice(sprintf(
|
|
__('Вы запросили %d шт., но доступно только %d. Добавлено максимально возможное количество.', 'woocommerce'),
|
|
$quantity, $can_add
|
|
), 'notice');
|
|
} else {
|
|
wc_add_notice(__('Вы не можете добавить больше — товар закончился на складе.', 'woocommerce'), 'error');
|
|
}
|
|
|
|
// Возвращаем false, чтобы остановить оригинальное добавление
|
|
return false;
|
|
}
|
|
|
|
return $passed;
|
|
}
|
|
|
|
// Убираем редирект на страницу товара при неудаче добавления
|
|
add_filter('woocommerce_cart_redirect_after_error', '__return_false');
|
|
|
|
add_action('wp_ajax_get_wc_notices', 'custom_get_wc_notices');
|
|
add_action('wp_ajax_nopriv_get_wc_notices', 'custom_get_wc_notices');
|
|
|
|
|
|
add_action('woocommerce_after_cart_item_quantity_update', 'custom_limit_cart_quantity_on_update', 20, 4);
|
|
function custom_limit_cart_quantity_on_update($cart_item_key, $quantity, $old_quantity, $cart) {
|
|
$cart_item = $cart->get_cart_item($cart_item_key);
|
|
if (!$cart_item) {
|
|
return;
|
|
}
|
|
|
|
$product = $cart_item['data'];
|
|
|
|
if (!$product->managing_stock()) {
|
|
return;
|
|
}
|
|
|
|
$stock = $product->get_stock_quantity();
|
|
|
|
if ($quantity > $stock) {
|
|
// Ограничим до доступного количества
|
|
$cart->set_quantity($cart_item_key, $stock);
|
|
|
|
wc_add_notice(sprintf(
|
|
__('Вы запросили %d шт., но доступно только %d. Количество было скорректировано.', 'woocommerce'),
|
|
$quantity, $stock
|
|
), 'notice');
|
|
}
|
|
}
|
|
|
|
|
|
|
|
function custom_get_wc_notices() {
|
|
ob_start();
|
|
wc_print_notices(); // выводим уведомления, если они есть
|
|
$html = ob_get_clean();
|
|
|
|
wp_send_json_success([
|
|
'html' => $html,
|
|
]);
|
|
}
|
|
|