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.
 
 
 
 
 
cosmopet.ae/wp-content/themes/woodmart/functions.php

1200 lines
48 KiB

<?php
// header('Cache-Control: max-age=3600, must-revalidate');
update_option( 'woodmart_token', true );
update_option( 'woodmart_is_activated', true );
update_option( 'woodmart_purchase_code', '********************************' );
global $main_host; // GP | Боевой домен
global $site_work_mode; // GP | Проверка на production и development версию сайта
/**
*
* The framework's functions and definitions
*/
define( 'WOODMART_THEME_DIR', get_template_directory_uri() );
define( 'WOODMART_THEMEROOT', get_template_directory() );
define( 'WOODMART_IMAGES', WOODMART_THEME_DIR . '/images' );
define( 'WOODMART_SCRIPTS', WOODMART_THEME_DIR . '/js' );
define( 'WOODMART_STYLES', WOODMART_THEME_DIR . '/css' );
define( 'WOODMART_FRAMEWORK', '/inc' );
define( 'WOODMART_DUMMY', WOODMART_THEME_DIR . '/inc/dummy-content' );
define( 'WOODMART_CLASSES', WOODMART_THEMEROOT . '/inc/classes' );
define( 'WOODMART_CONFIGS', WOODMART_THEMEROOT . '/inc/configs' );
define( 'WOODMART_HEADER_BUILDER', WOODMART_THEME_DIR . '/inc/header-builder' );
define( 'WOODMART_ASSETS', WOODMART_THEME_DIR . '/inc/admin/assets' );
define( 'WOODMART_ASSETS_IMAGES', WOODMART_ASSETS . '/images' );
define( 'WOODMART_API_URL', 'https://xtemos.com/licenses/api/' );
define( 'WOODMART_DEMO_URL', 'https://woodmart.xtemos.com/' );
define( 'WOODMART_PLUGINS_URL', WOODMART_DEMO_URL . 'plugins/' );
define( 'WOODMART_DUMMY_URL', WOODMART_DEMO_URL . 'dummy-content-new/' );
define( 'WOODMART_TOOLTIP_URL', WOODMART_DEMO_URL . 'theme-settings-tooltips/' );
define( 'WOODMART_SLUG', 'woodmart' );
define( 'WOODMART_CORE_VERSION', '1.0.39' );
define( 'WOODMART_WPB_CSS_VERSION', '1.0.3' );
define( 'SECRET', 'fT54ehYtt87@q1A' );
if ( ! function_exists( 'woodmart_load_classes' ) ) {
function woodmart_load_classes() {
$classes = array(
'Singleton.php',
'Api.php',
'Googlefonts.php',
'Config.php',
'Layout.php',
'License.php',
'Notices.php',
'Options.php',
'Stylesstorage.php',
'Theme.php',
'Themesettingscss.php',
'Vctemplates.php',
'Wpbcssgenerator.php',
'Registry.php',
'Pagecssfiles.php',
);
foreach ( $classes as $class ) {
require WOODMART_CLASSES . DIRECTORY_SEPARATOR . $class;
}
}
}
woodmart_load_classes();
new WOODMART_Theme();
define( 'WOODMART_VERSION', woodmart_get_theme_info( 'Version' ) );
add_action( 'init', 'my_deregister_heartbeat', 1 );
function my_deregister_heartbeat() {
global $pagenow;
if ( 'post.php' != $pagenow && 'post-new.php' != $pagenow )
wp_deregister_script('heartbeat');
}
add_action( 'wp_enqueue_scripts', 'gp_front_page_scripts' );
function gp_front_page_scripts() {
wp_enqueue_style( 'gp-fonts', get_template_directory_uri() . '/gp-include/assets/core/css/fonts.css?v=1.05' );
wp_enqueue_style( 'gp-core', get_template_directory_uri() . '/gp-include/assets/core/css/core.css?v=1.34' );
wp_enqueue_style( 'gp-header', get_template_directory_uri() . '/gp-include/assets/core/css/gp-header.css?v=1.14' );
wp_enqueue_style( 'gp-footer', get_template_directory_uri() . '/gp-include/assets/core/css/gp-footer.css?v=1.09' );
wp_enqueue_style( 'gp-core-adaptive', get_template_directory_uri() . '/gp-include/assets/core/css/core-adaptive.css?v=1.18' );
wp_enqueue_style( 'gp-header-adaptive', get_template_directory_uri() . '/gp-include/assets/core/css/header-adaptive.css?v=1.09' );
wp_enqueue_style( 'gp-footer-adaptive', get_template_directory_uri() . '/gp-include/assets/core/css/footer-adaptive.css?v=1.22' );
// wp_enqueue_style( 'gp-frnt-page-style', get_template_directory_uri() . '/gp-include/assets/front-page/css/style.css?v=1.139' );
// wp_enqueue_script( 'gp-front-page-script', get_template_directory_uri() . '/gp-include/assets/front-page/js/main.js?v=1.022', array(), null, true );
// wp_enqueue_style( 'gp-front-page-style-mobile-menu', get_template_directory_uri() . '/gp-include/assets/front-page/css/style-mobile-menu.css?v=1.01' );
// wp_enqueue_style( 'gp-front-page-style-adaptive', get_template_directory_uri() . '/gp-include/assets/front-page/css/style-adaptive.css?v=1.01' );
// wp_enqueue_style( 'gp-front-page-style-adaptive-mobile', get_template_directory_uri() . '/gp-include/assets/front-page/css/style-adaptive-mobile.css' );
// wp_enqueue_style( 'gp-front-page-carousel', get_template_directory_uri() . '/gp-include/assets/front-page/css/carousel.css' );
wp_enqueue_style( 'int-tel','https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.0/css/intlTelInput.css' );
wp_enqueue_script( 'int-tel-js', 'https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.0/js/intlTelInput.min.js');
wp_enqueue_script( 'int-tel-js-ru', 'https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/24.7.0/build/js/i18n/ru/countries.min.js');
wp_enqueue_script( 'mask', 'https://cdnjs.cloudflare.com/ajax/libs/jquery.maskedinput/1.4.1/jquery.maskedinput.min.js');
wp_enqueue_style( 'gp-catalog-style', get_template_directory_uri() . '/gp-include/assets/catalog/css/style.css?v=1.13' );
wp_enqueue_style( 'gp-common-page-style', get_template_directory_uri() . '/gp-include/assets/common/css/style.css?v=1.10' );
wp_enqueue_style( 'gp-catalog-style', get_template_directory_uri() . '/gp-include/assets/catalog/css/style.css?v=1.03' );
wp_enqueue_style( 'gp-catalog-adapt-style', get_template_directory_uri() . '/gp-include/assets/catalog/css/adaptive.css?v=1.05' );
wp_enqueue_script( 'gp-form', get_template_directory_uri() . '/gp-include/assets/core/js/gp-form.js?v=1.33', array(), null, true );
if(is_page_template('gp-front-page.php') || is_page_template('gp-front-page_eng.php')){
// CSS
wp_enqueue_style( 'gp-front-page-swiper', get_template_directory_uri() . '/gp-include/assets/front-page/css/swiper-bundle.min.css' );
wp_enqueue_style( 'gp-frnt-page-style', get_template_directory_uri() . '/gp-include/assets/front-page/css/style.css?v=1.47' );
wp_enqueue_script( 'gp-front-page-script', get_template_directory_uri() . '/gp-include/assets/front-page/js/main.js?v=1.34', array(), null, true );
// wp_enqueue_style( 'gp-front-page-style-mobile-menu', get_template_directory_uri() . '/gp-include/assets/front-page/css/style-mobile-menu.css?v=1.01' );
wp_enqueue_style( 'gp-front-page-style-adaptive', get_template_directory_uri() . '/gp-include/assets/front-page/css/style-adaptive.css?v=1.02' );
wp_enqueue_style( 'gp-front-page-style-adaptive-mobile', get_template_directory_uri() . '/gp-include/assets/front-page/css/style-adaptive-mobile.css?v=1.02' );
wp_enqueue_style( 'gp-front-page-carousel', get_template_directory_uri() . '/gp-include/assets/front-page/css/carousel.css' );
// JS
wp_enqueue_script( 'gp-front-page-swiper', get_template_directory_uri() . '/gp-include/assets/front-page/js/swiper-bundle.min.js', array(), null, true );
wp_enqueue_script( 'gp-front-page-materialize', get_template_directory_uri() . '/gp-include/assets/front-page/js/materialize.min.js', array(), null, true );
/* Сокращение до N слов -- не работает( */
add_filter('excerpt_length', 'new_excerpt_length', 999);
function new_excerpt_length($length) {
return 13;
}
}
else if (is_page_template('gp-about-page.php') || is_page_template('gp-about-page_eng.php')){
wp_enqueue_style( 'gp-front-page-swiper', get_template_directory_uri() . '/gp-include/assets/front-page/css/swiper-bundle.min.css' );
wp_enqueue_style( 'gp-about-page-style', get_template_directory_uri() . '/gp-include/assets/about/css/style.css?v=1.08' );
wp_enqueue_style( 'gp-about-page-style-adapt', get_template_directory_uri() . '/gp-include/assets/about/css/style-adaptive.css?v=1.18' );
wp_enqueue_script( 'gp-front-page-swiper', get_template_directory_uri() . '/gp-include/assets/front-page/js/swiper-bundle.min.js', array(), null, true );
wp_enqueue_script( 'gp-about-page-script', get_template_directory_uri() . '/gp-include/assets/about/js/script.js', array(), null, true );
wp_enqueue_script( 'gp-front-page-materialize', get_template_directory_uri() . '/gp-include/assets/front-page/js/materialize.min.js', array(), null, true );
}
else if (is_product_category() || is_single('product')){
wp_enqueue_style( 'gp-common-page-style-adapt', get_template_directory_uri() . '/gp-include/assets/common/css/adaptive.css?v=1.13' );
wp_enqueue_style( 'gp-detail', get_template_directory_uri() . '/gp-include/assets/front-page/css/gp-detail.css?v=1.13' );
wp_enqueue_script( 'gp-front-page-swiper', get_template_directory_uri() . '/gp-include/assets/common/js/swiper-bundle.min.js', array(), null, true );
wp_enqueue_script( 'gp-front-page-script', get_template_directory_uri() . '/gp-include/assets/common/js/main.js', array(), null, true );
wp_enqueue_script( 'gp-front-page-materialize', get_template_directory_uri() . '/gp-include/assets/common/js/materialize.min.js', array(), null, true );
}
else if (is_page_template('gp-prod-page.php') || is_page_template('gp-prod-page_eng.php')){
wp_enqueue_style( 'gp-front-page-swiper', get_template_directory_uri() . '/gp-include/assets/front-page/css/swiper-bundle.min.css' );
wp_enqueue_style( 'gp-prod-page-style', get_template_directory_uri() . '/gp-include/assets/production/css/style.css?v=1.02' );
wp_enqueue_style( 'gp-frnt-page-style', get_template_directory_uri() . '/gp-include/assets/front-page/css/style.css?v=1.18' );
wp_enqueue_script( 'gp-front-page-script', get_template_directory_uri() . '/gp-include/assets/front-page/js/main.js?v=1.023', array(), null, true );
// wp_enqueue_style( 'gp-front-page-style-mobile-menu', get_template_directory_uri() . '/gp-include/assets/front-page/css/style-mobile-menu.css?v=1.01' );
wp_enqueue_style( 'gp-front-page-style-adaptive', get_template_directory_uri() . '/gp-include/assets/front-page/css/style-adaptive.css?v=1.01' );
wp_enqueue_style( 'gp-front-page-style-adaptive-mobile', get_template_directory_uri() . '/gp-include/assets/front-page/css/style-adaptive-mobile.css' );
wp_enqueue_style( 'gp-front-page-carousel', get_template_directory_uri() . '/gp-include/assets/front-page/css/carousel.css' );
// JS
wp_enqueue_script( 'gp-front-page-swiper', get_template_directory_uri() . '/gp-include/assets/front-page/js/swiper-bundle.min.js', array(), null, true );
wp_enqueue_script( 'gp-prod-page-script', get_template_directory_uri() . '/gp-include/assets/production/js/script.js', array(), null, true );
wp_enqueue_script( 'gp-front-page-materialize', get_template_directory_uri() . '/gp-include/assets/front-page/js/materialize.min.js', array(), null, true );
}
else if(is_account_page()){
wp_enqueue_style( 'gp-account-style', get_template_directory_uri() . '/gp-include/assets/lk/css/style.css?v=1.21' );
wp_enqueue_style( 'gp-account-style-mob', get_template_directory_uri() . '/gp-include/assets/lk/css/style-adaptive.css?v=1.19' );
wp_enqueue_script( 'gp-account', get_template_directory_uri() . '/gp-include/assets/lk/js/script.js?v=1.09', array(), null, true );
}
else{
wp_enqueue_style( 'gp-catalog-style', get_template_directory_uri() . '/gp-include/assets/catalog/css/style.css?v=1.04' );
wp_enqueue_style( 'gp-catalog-adapt-style', get_template_directory_uri() . '/gp-include/assets/catalog/css/adaptive.css?v=1.03' );
wp_enqueue_script( 'gp-front-page-script', get_template_directory_uri() . '/gp-include/assets/common/js/main.js', array(), null, true );
}
wp_enqueue_script('jq-cookie', 'https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js');
wp_enqueue_script( 'gp-core-script', get_template_directory_uri() . '/gp-include/assets/core/js/core.js?v=1.22', array(), null, true );
if(is_singular('product')){
wp_enqueue_style( 'gp-front-page-swiper', get_template_directory_uri() . '/gp-include/assets/front-page/css/swiper-bundle.min.css' );
wp_enqueue_script( 'gp-front-page-swiper', get_template_directory_uri() . '/gp-include/assets/common/js/swiper-bundle.min.js', array(), null, true );
wp_enqueue_script( 'gp-product-script', get_template_directory_uri() . '/gp-include/assets/core/js/gp-product.js', array(), null, true );
}
// if($_SERVER['REQUEST_URI'] == '/blog/'){
// wp_enqueue_style( 'gp-front-page-swiper', get_template_directory_uri() . '/woodmart/css/parts/base.min.css' );
// }
}
/* Кастомный тег <img> для Contact Form 7 */
function custom_add_form_tag_img_handler( $tag ) {
return '<img src="' . get_stylesheet_directory_uri() . '/' . $tag['options'][0] . '">';
}
function custom_add_form_tag_img() {
wpcf7_add_form_tag( 'img', 'custom_add_form_tag_img_handler' );
}
add_action( 'wpcf7_init', 'custom_add_form_tag_img' );
add_action( 'wpcf7_before_send_mail',
function( $contact_form, &$abort, $submission ) {
$form_id = WPCF7_ContactForm::get_current();
if ($form_id->id == 17302) {
$sub = $submission->get_posted_data( 'subscriber' );
$url = 'https://api.mindbox.ru/v3/operations/async?endpointId=cosmopet.Website&operation=PolzovatelyaSSajtaStatForma';
$data = array(
"email" => $sub,
"subscriptions" => array(
array(
"pointOfContact"=> "Email"
),
),
);
$data_string = json_encode(array("customer" =>$data));
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
}
},
10, 3
);
add_action( 'wp_ajax_subform', 'subform_callback' );
add_action( 'wp_ajax_nopriv_subform', 'subform_callback' );
function subform_callback(){
$url = 'https://api.mindbox.ru/v3/operations/async?endpointId=cosmopet.Website&operation=DobavleniePolzovatelyaSSajta';
$data = array(
"email" => $_POST['email'],
"name" => $_POST['name'],
"subscriptions" => array(
array(
"pointOfContact"=> "Email"
),
),
);
$data_string = json_encode(array("customer" =>$data));
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
wp_die();
}
add_action( 'wp_ajax_message', 'message_callback' );
add_action( 'wp_ajax_nopriv_message', 'message_callback' );
function message_callback(){
$phone = $_POST['phone'];
$name = $_POST['name'];
$email = $_POST['email'];
$msg = $_POST['msg'];
$message = 'Имя - ' . $name . '
email - ' . $email . '
phone - ' . $phone . '
сообщение - ' . $msg;
$headers = array(
'From: Cosmopet <pro@cosmopet.shop>',
'content-type: text/html; charset=utf-8',
);
wp_mail('partners@cosmopet.ae', 'Сообщение с сайта Cosmopet', $message, $headers);
wp_die();
}
add_action( 'wp_ajax_product_subform', 'product_subform_callback' );
add_action( 'wp_ajax_nopriv_product_subform', 'product_subform_callback' );
function product_subform_callback(){
$dateTimeString = gmdate('Y-m-d H:i:s');
$sub = $_POST['email'];
$url = 'https://api.mindbox.ru/v3/operations/sync?endpointId=cosmopet.Website&operation=UnauthUserDataGet';
$data = array(
"email" => $sub,
);
$data_string = json_encode(array("customer" =>$data));
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = json_decode(curl_exec($ch));
curl_close($ch);
if ($result->customer->customFields->productInStock){
$current_subs = $result->customer->customFields->productInStock;
$current_subs[] = $_POST['product_name'];
$url = 'https://api.mindbox.ru/v3/operations/sync?endpointId=cosmopet.Website&operation=UserDataEdit';
$data = array(
"email" => $sub,
'customFields' => array(
"productInStock" => $current_subs,
),
);
$data_string = json_encode(array("customer" =>$data));
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = json_decode(curl_exec($ch));
curl_close($ch);
}
else{
$url = 'https://api.mindbox.ru/v3/operations/async?endpointId=cosmopet.Website&operation=DobavleniePolzovatelyaSSajta';
$data = array(
"email" => $sub,
"subscriptions" => array(
array(
"pointOfContact"=> "Email"
),
),
'customFields' => array(
"productInStock" => array(
$_POST['product_name'],
),
),
);
$data_string = json_encode(array("customer" =>$data));
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = json_decode(curl_exec($ch));
curl_close($ch);
}
wp_die();
}
add_action( 'wp_ajax_subscription_sub__profile', 'subscription_sub__profile' );
add_action( 'wp_ajax_nopriv_subscription_sub__profile', 'subscription_sub__profile' );
function subscription_sub__profile(){
$url = 'https://api.mindbox.ru/v3/operations/async?endpointId=cosmopet.Website&operation=DobavleniePolzovatelyaSSajta';
$data = array(
"email" => $_POST['email'],
"subscriptions" => array(
array(
"pointOfContact"=> "Email"
),
),
'customFields' => array(
"foodSub" => true,
),
);
$data_string = json_encode(array("customer" =>$data));
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = json_decode(curl_exec($ch));
curl_close($ch);
wp_die();
}
//Не отправляем письма на почту через WPCF
// function my_skip_mail($skip_mail, $contact_form) {
// if($site_work_mode != 'production'){
// $skip_mail = true; // true skips sending the email
// }
// return $skip_mail;
// }
add_filter( 'wpcf7_skip_mail','my_skip_mail', PHP_INT_MAX, 2 );
add_action('init', function(){
register_post_type('smi', array(
'labels' => array(
'name' => 'СМИ о нас',
),
'public' => false,
'supports' => array('title', 'thumbnail'),
'show_ui' => true,
'has_archive' => false,
));
});
add_filter('pll_get_post_types', 'add_cpt_to_pll', 10, 2);
function add_cpt_to_pll($post_types, $hide) {
if ($hide)
// hides 'my_cpt' from the list of custom post types in Polylang settings
unset($post_types['smi']);
else
// enables language and translation management for 'my_cpt'
$post_types['smi'] = 'smi';
$post_types['wpcf7'] = 'wpcf7';
return $post_types;
}
// add_action( 'woocommerce_product_query', 'custom_woocommerce_product_query' );
// function custom_woocommerce_product_query ($q) {
// $q->set( 'post_type', array( 'product', 'product_variation' ) );
// return $q;
// }
add_action('wp_ajax_woocommerce_ajax_upd_cart_contents', 'woocommerce_ajax_upd_cart_contents');
add_action('wp_ajax_nopriv_woocommerce_ajax_upd_cart_contents', 'woocommerce_ajax_upd_cart_contents');
function woocommerce_ajax_upd_cart_contents() {
ob_start();
get_cart_template();
// записываем всё, что в буфере, в переменную
$html_cart = ob_get_contents();
// очищаем буфер
ob_end_clean();
$data = array(
'cart' => $html_cart,
'cart_count' => WC()->cart->get_cart_contents_count(),
);
echo wp_send_json($data);
}
add_action('wp_ajax_get_cartprice', 'woocommerce_get_cartprice');
add_action('wp_ajax_nopriv_get_cartprice', 'woocommerce_get_cartprice');
function woocommerce_get_cartprice() {
global $woocommerce;
$cart_item_key = $_POST['product'];
$quantity = $_POST['quantity'];
WC()->cart->set_quantity($cart_item_key, $quantity);
$total = $woocommerce->cart->get_subtotal();
$html_cart = '';
if($total == 0){
ob_start();
get_cart_template();
// записываем всё, что в буфере, в переменную
$html_cart = ob_get_contents();
// очищаем буфер
ob_end_clean();
}
wp_send_json( array(
'total' => $total,
'cart' => $html_cart,
'cart_count' => WC()->cart->get_cart_contents_count(),
));
}
function get_cart_template(){
global $woocommerce;
WC()->cart->calculate_totals();
$items = $woocommerce->cart->get_cart();
?>
<button class="modal__close">
<img src="<?= get_template_directory_uri();?>/gp-include/assets/core/img/svg/main/black-x.svg" alt="">
</button>
<?php
if (count($items) > 0):
?>
<div class="modal__header">
<p class="modal__title"><?php echo esc_html__( 'Cart', 'woodmart' ) ?></p>
<div class="modal__content">
<?php
foreach($items as $item => $values):
// var_dump($values['data']);
$_product = apply_filters( 'woocommerce_cart_item_product', $values['data'], $values, $item );
$product_id = apply_filters( 'woocommerce_cart_item_product_id', $values['product_id'], $values, $item );
?>
<?
$_varID = $values['variation_id'];
if ($_varID){
$variation_obj = new WC_Product_Variation($_varID);
$wg = $variation_obj->get_weight();
}
else{
$wg = '';
}
$p_id = $_varID;
if (!$_varID){
$_varID = 0;
$p_id = $values['product_id'];
}
$post_thumbnail_id = $_product->get_image_id();
$quantity = $values['quantity'];
//$price = get_post_meta($p_id , '_price', true);
$price = $_product->get_price();
$key = $values["key"];
// $wg = '';
// if ($_product->is_type('variable')){
// $wg = $_product->get_weight();
// }
?>
<div class="modal-basket__item cart_item" data-cost="<?= $quantity * $price ?>">
<div class="modal-basket-item__block-image">
<img src="<?php echo wp_get_attachment_url( $post_thumbnail_id ); ?>" alt="" class="modal-basket-item__image">
</div>
<div class="modal-basket__item-before" data-id="<?= $key ?>" data-pr="<?= $_product->get_ID() ?>" data-var="<?= $_varID ?>">
</div>
<div class="modal-basket-item__content">
<p class="modal-basket-item__title"><?= $_product->get_title() ?></p>
<p class="modal-basket-item__sub-title"><?php if ($wg){ echo $wg . esc_html__( 'kg', 'woodmart' );} ?></p>
<div class="modal-basket-item__control">
<div class="counter counter--small">
<button data-id="<?= $key ?>" class="counter__button minus" data-value="<?= $quantity ?>" type="button">
<img src="<?= get_template_directory_uri();?>/gp-include/assets/core/img/svg/main/minus.svg" alt="">
</button>
<input type="text" class="counter__input cart_item_quantity" data-maxcount="<?php echo $_product->get_stock_quantity() ?>" value="<?= $quantity ?>">
<button data-id="<?= $key ?>" class="counter__button plus" type="button">
<img src="<?= get_template_directory_uri();?>/gp-include/assets/core/img/svg/main/plus.svg" alt="">
</button>
</div>
<p class="modal-basket-item__price product-subtotal" data-basecost="<?php echo $price ?>"><?= $quantity * $price ?></p>
</div>
</div>
</div>
<?php
endforeach;
?>
</div>
</div>
<div class="modal__footer">
<div class="modal__block-price">
<p class="modal-block-price__title"><?php echo esc_html__( 'Subtotal', 'woodmart' ) ?></p>
<p class="modal-block-price__price" id="cart_total">
<?php echo $woocommerce->cart->get_subtotal(); ?>
</p>
</div>
<div class="modal__block-button">
<div class="modal__button">
<a href="<?php echo wc_get_checkout_url() ?>" class="button button--gradient button--high button--100-perc">
<?php echo esc_html__( 'Checkout', 'woodmart' ) ?>
</a>
</div>
</div>
</div>
<?php
else:
?>
<div class="modal__header --nb">
<p class="modal__title"><?php echo esc_html__( 'Cart', 'woodmart' ) ?></p>
<p class="modal__text"><?php echo esc_html__( 'Your cart is empty', 'woodmart' ) ?></p>
</div>
<div class="modal__footer">
<div class="modal__block-button">
<div class="modal__button">
<a href="<?php echo get_permalink( wc_get_page_id( 'shop' ) ) ?>" class="button button--100-perc button--link button--white">
<?php echo esc_html__( 'Continue shopping', 'woodmart' ) ?>
</a>
</div>
</div>
</div>
<?php
endif;
}
add_action('wp_ajax_get_cart_layout', 'woocommerce_get_cart_layout');
add_action('wp_ajax_nopriv_get_cart_layout', 'woocommerce_get_cart_layout');
function woocommerce_get_cart_layout() {
get_cart_template();
wp_die();
}
// Change the Number of WooCommerce Products Displayed Per Page
add_filter( 'loop_shop_per_page', 'lw_loop_shop_per_page', 30 );function lw_loop_shop_per_page( $products ) { $products = 12; return $products;}
function be_product_query( $query ) {
if( $query->is_main_query() && !$query->is_feed() && !is_admin() && $query->is_post_type_archive( 'product' ) ) {
$meta_query = array(
array(
)
);
$args = array(
'post_type' => 'product',
'posts_per_page' => -1,
'orderby' => 'date',
'order' => 'DESC',
'tax_query' => array(
'relation' => 'AND',
)
);
$has_variable_ids = array();
$simple_ids = array();
$args[ 'tax_query' ]['relation'] = 'AND';
if (isset($_GET['for_whom'])){
$args[ 'tax_query' ][] = array(
'taxonomy' => 'pa_dlya-kogo',
'field' => 'slug',
'terms' => array($_GET['for_whom']),
);
}
if (isset($_GET['product_type'])){
$args[ 'tax_query' ][] = array(
'taxonomy' => 'pa_pr_type',
'field' => 'slug',
'terms' => array($_GET['product_type']),
);
}
$pubished_post = new WP_Query($args);
if (!empty($pubished_post->posts))
{
foreach ($pubished_post->posts as $pr)
{
$_product = wc_get_product($pr->ID);
if ($_product->is_type('variable'))
{
// Product has variations
$has_variable_ids[] = $pr->ID;
}
else{
$simple_ids[] = $pr->ID;
}
}
}
// var_dump($has_variable_ids);
// var_dump($simple_ids);
$query->set( 'post_parent__in', $has_variable_ids );
$query->set( 'post_type', array('product', 'product_variation') );
// $query->set('meta_query', $meta_query);
}
}
add_action( 'pre_get_posts', 'be_product_query' );
// Отправка кода и проверка Email
add_action( 'wp_ajax_email_validate', 'email_validate' );
add_action( 'wp_ajax_nopriv_email_validate', 'email_validate' );
function email_validate(){
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) {
header("Content-Type: application/json");
echo json_encode(array(
'status' => 'error',
'text' => esc_html__( 'Invalid email format', 'woodmart' )
));
}
wp_die();
}
add_action( 'wp_ajax_send_code', 'send_code' );
add_action( 'wp_ajax_nopriv_send_code', 'send_code' );
function send_code(){
$email = $_POST['email'];
$string = rand(1234,9999);
$ciphering = "AES-128-CTR";
$options = 0;
$iv = '1234567891011121';
$encryption = openssl_encrypt($string, $ciphering, SECRET, $options, $iv);
setcookie('login_code', $encryption, time()+60*5, '/');
if(pll_current_language() === 'ru'){
$subject = "Проверочный код Cosmopet -".$string;
$message = "Привет, это Cosmopet.\n
Держите проверочный код!\n
".$string;
} else {
$subject = "Cosmopet Verification Code -".$string;
$message = "Hello, this is CosmoPet.\n
Here's your verification code!\n
".$string;
}
remove_all_filters( 'wp_mail_from' );
remove_all_filters( 'wp_mail_from_name' );
$headers = array(
'From: Cosmopet <pro@cosmopet.shop>',
'content-type: text/html; charset=utf-8',
);
wp_mail( $email, $subject, $message, $headers );
wp_die();
}
// Проверка кода
add_action( 'wp_ajax_check_code', 'check_code' );
add_action( 'wp_ajax_nopriv_check_code', 'check_code' );
function check_code(){
header("Content-Type: application/json");
$code = $_POST['code'];
$email = $_POST['email'];
// Генерация пароля
$alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890@#!()';
$pass = array();
$alphaLength = strlen($alphabet) - 1;
for ($i = 0; $i < 12; $i++) {
$n = rand(0, $alphaLength);
$pass[] = $alphabet[$n];
}
$pass = implode($pass);
if(isset($_COOKIE['login_code'])) {
$string = $_COOKIE['login_code'];
$ciphering = "AES-128-CTR";
$options = 0;
$iv = '1234567891011121';
$decryption = openssl_decrypt($string, $ciphering, SECRET, $options, $iv);
if($decryption === $code){
if(email_exists($email)){
//Авторизуемся
$user_id = get_user_by( 'login', $email )->ID;
if(empty($user_id)) {
$user_id = get_user_by( 'email', $email )->ID;
}
wp_set_password( $pass, $user_id );
wp_signon(
array(
'user_login' => $email,
'user_password' => $pass,
'remember' => 'on',
)
);
echo json_encode(array(
'status' => 'success_auth'
));
update_field('activated', true, 'user_' . $user_id);
exit();
} else {
// Регистрируемся
$user_id = wp_create_user( $email , $pass , $email );
wp_update_user( [
'ID' => $user_id,
'user_email' => $email
] );
wp_set_auth_cookie( $user_id, true );
echo json_encode(array(
'status' => 'success_reg'
));
update_field('activated', true, 'user_' . $user_id);
exit();
}
} else {
echo json_encode(array(
'status' => 'error',
'text' => esc_html__( 'Invalid code', 'woodmart' )
));
exit();
}
} else {
echo 'nocoockie';
echo json_encode(array(
'status' => 'error',
'text' => esc_html__( 'The code has expired', 'woodmart' )
));
exit();
}
wp_die();
}
add_action( 'wp_logout', 'logout_redirect');
function logout_redirect(){
wp_redirect( '/' );
exit();
}
require_once( get_template_directory() . '/gp-include/php/multi-currency.php');
require_once( get_template_directory() . '/gp-include/php/pets.php');
require_once( get_template_directory() . '/gp-include/php/user.php');
require_once( get_template_directory() . '/gp-include/php/gp-checkout.php');
require_once( get_template_directory() . '/gp-include/php/gp-filter.php');
require_once( get_template_directory() . '/gp-include/php/tg/login.php');
add_action('init', 'custom_register_activation_endpoint');
function custom_register_activation_endpoint() {
add_rewrite_rule('^activate/([^/]*)/?', 'index.php?activation_key=$matches[1]', 'top');
add_rewrite_tag('%activation_key%', '([^&]+)');
}
add_action('template_redirect', 'custom_handle_activation_request');
function get_user_by_acf_field_value($field_value) {
// Prepare the arguments for WP_User_Query
$args = array(
'meta_query' => array(
array(
'key' => 'uuid', // Change to your ACF field key
'value' => $field_value,
'compare' => '=', // You can use other comparison operators if needed
),
),
);
// Execute the query
$user_query = new WP_User_Query($args);
// Check for results
if (!empty($user_query->get_results())) {
return $user_query->get_results(); // Returns an array of WP_User objects
} else {
return null; // No users found
}
}
function custom_handle_activation_request() {
if (get_query_var('activation_key')) {
$activation_key = sanitize_text_field(get_query_var('activation_key'));
$users = get_user_by_acf_field_value($activation_key);
if ($users) {
foreach ($users as $user) {
$user->set_bio();
// delete_user_meta($user->ID, 'uuid'); // Clean up the activation key
update_field('uuid', '', 'user_' . $user->ID);
update_field('activated', true, 'user_' . $user->ID);
wp_set_auth_cookie($user->ID);
wp_redirect('/my-account/'); // Redirect to the homepage or a custom page
var_dump($user);
exit;
}
}
}
}
// Отправка кода и проверка Email
add_action( 'wp_ajax_email_activate', 'send_activation_email' );
add_action( 'wp_ajax_nopriv_email_activate', 'send_activation_email' );
function send_activation_email() {
$user = wp_get_current_user();
$activation_key = sha1($user->user_email . time()); // Generate a unique activation key
update_field('uuid', $activation_key, 'user_' . get_current_user_id()); // Save the key in user meta
$activation_link = home_url("/activate/$activation_key");
if(pll_current_language() === 'ru'){
$subject = "Активация аккаунта COSMOPET -".$string;
$message = " Остался последний шаг!\n
Пройдите по ссылке для активации аккаунта:\n
".$activation_link;
} else {
$subject = "Account activation COSMOPET -".$string;
$message = "Last step!\n
Follow the link to activate your account\n
".$activation_link;
}
wp_mail($user->user_email, $subject, $message);
}
// Отключить уведомления по электронной почте при регистрации пользователя
add_filter('new_user_notification_email', '__return_false');
add_action('user_register', 'custom_new_customer_email', 10, 2);
function custom_new_customer_email($customer_id) {
$user = get_userdata($customer_id);
$site_name = get_bloginfo('name');
$to = $user->user_email;
if(pll_current_language() === 'ru'){
// Ваш текст письма
$subject = 'Добро пожаловать в COSMOPET';
$message = "Приветствуем вас на борту Cosmopet!\n
Рады держать вас в курсе наших новостей и акций.\n
P.S. Обещаем писать только по делу.";
}
else{
$subject = 'Welcome to COSMOPET';
$message = "Welcome aboard CosmoPet! \n
We are happy to keep you updated on our news, events and promos.\n
P.S. We promise to write only to the point";
}
// Убедитесь, что письма отправляются в правильном формате
$headers = array('Content-Type: text/plain; charset=UTF-8');
// Отправка письма
wp_mail($to, $subject, $message, $headers);
}
// if ( !function_exists('wp_new_user_notification') ) {
// function wp_new_user_notification( $user_id, $plaintext_pass = '' ) {
// $user = new WP_User($user_id);
// $to = stripslashes($user->user_email);
// if(pll_current_language() === 'ru'){
// // Ваш текст письма
// $subject = 'Добро пожаловать в COSMOPET';
// $message = "Приветствуем вас на борту Cosmopet!\n
// Рады держать вас в курсе наших новостей и акций.\n
// P.S. Обещаем писать только по делу.";
// }
// else{
// $subject = 'Welcome to COSMOPET';
// $message = "Welcome aboard CosmoPet! \n
// We are happy to keep you updated on our news, events and promos.\n
// P.S. We promise to write only to the point";
// }
// // Убедитесь, что письма отправляются в правильном формате
// $headers = array('Content-Type: text/plain; charset=UTF-8');
// // Отправка письма
// wp_mail($to, $subject, $message, $headers);
// }
// }
add_filter('woocommerce_get_catalog_ordering_args', 'custom_woocommerce_catalog_ordering_args');
function custom_woocommerce_catalog_ordering_args($args) {
$args['orderby'] = 'date'; // Сортируем по дате
$args['order'] = 'DESC'; // Последние добавленные первыми
return $args;
}
add_filter('woocommerce_currency_symbol', 'change_existing_currency_symbol', 10, 2);
function change_existing_currency_symbol( $currency_symbol, $currency ) {
$currency_symbol = 'AED';
return $currency_symbol;
}
// ADD TO CART DUNCTION CUSTOM
add_action('wp_ajax_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart');
add_action('wp_ajax_nopriv_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart');
function woocommerce_ajax_add_to_cart() {
$product_id = apply_filters('woocommerce_add_to_cart_product_id', absint($_POST['product_id']));
$quantity = empty($_POST['quantity']) ? 1 : wc_stock_amount($_POST['quantity']);
$variation_id = absint($_POST['variation_id']);
$passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity);
$product_status = get_post_status($product_id);
if($variation_id){
$obj = new WC_Product_Variation($variation_id);
$stock = $obj->get_stock_quantity();
if ($quantity > $stock){
$quantity = $stock;
}
}
else{
$obj = wc_get_product( $product_id );
$stock = $obj->get_stock_quantity();
if ($quantity > $stock){
$quantity = $stock;
}
}
if ($passed_validation && WC()->cart->add_to_cart($product_id, $quantity, $variation_id) && 'publish' === $product_status) {
do_action('woocommerce_ajax_added_to_cart', $product_id);
if ('yes' === get_option('woocommerce_cart_redirect_after_add')) {
wc_add_to_cart_message(array($product_id => $quantity), true);
}
ob_start();
get_cart_template();
// записываем всё, что в буфере, в переменную
$html_cart = ob_get_contents();
// очищаем буфер
ob_end_clean();
}
$data = array(
'cart' => $html_cart,
'cart_count' => WC()->cart->get_cart_contents_count(),
);
echo wp_send_json($data);
}
// Удаляет графу доставка из страницы успешного заказа
add_filter('woocommerce_order_details_after_order_table', 'custom_hide_shipping_info', 10, 1);
function custom_hide_shipping_info($order) {
// Удаляем строку с информацией о доставке
remove_action('woocommerce_order_details_after_order_table', 'woocommerce_order_shipping_info', 10);
}
// add_filter('woocommerce_add_error', function($error) {
// if($error === 'An account is already registered with your email address. <a href="#" class="showlogin">Please log in.</a>') {
// return 'An account is already registered with your email address. <a onclick="alert(1)" class="login-open">Please log in.</a>';
// }
// return $error;
// });
add_filter('woocommerce_registration_error_email_exists', 'custom_email_exists_error_message', 10, 2);
function custom_email_exists_error_message($default_message, $email) {
// Ваше кастомное сообщение об ошибке
$custom_message = __('An account is already registered with your email address. <a class="please-login">Please log in.</a>', 'woocommerce');
return $custom_message;
}
add_filter('woocommerce_apply_coupon', 'limit_to_one_coupon', 10, 3);
add_action( 'woocommerce_before_calculate_totals', 'one_applied_coupon_only', 10, 1 );
function one_applied_coupon_only( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// For more than 1 applied coupons only
if ( sizeof($cart->get_applied_coupons()) > 1 && $coupons = $cart->get_applied_coupons() ){
// Remove the first applied coupon keeping only the last appield coupon
$cart->remove_coupon( reset($coupons) );
}
}
add_action('wp_footer', 'add_facebook_pixel_events');
function add_facebook_pixel_events() {
// 1. Событие AddToCart (Добавление в корзину)
// Предполагаем, что кнопка имеет класс 'add_to_cart_button' (стандарт WooCommerce)
if (is_product() || is_shop() || is_cart()) { // Только на страницах товаров, магазина или корзины
?>
<script>
document.addEventListener('DOMContentLoaded', function() {
var buttons = document.querySelectorAll('.add_to_cart_button');
buttons.forEach(function(button) {
button.addEventListener('click', function() {
fbq('track', 'AddToCart');
});
});
});
</script>
<?php
}
// 2. Событие Purchase (Покупка)
// На странице https://cosmopet.ae/checkout/order-received
if (strpos($_SERVER['REQUEST_URI'], '/checkout/order-received') !== false) {
?>
<script>
// document.addEventListener('DOMContentLoaded', function() {
// if (!sessionStorage.getItem('purchase_tracked')) {
// var urlParams = new URLSearchParams(window.location.search);
// var orderId = urlParams.get('order_id') || urlParams.get('key');
// if (orderId) {
// fbq('track', 'Purchase', {
// value: 0.00,
// currency: 'AED'
// });
// sessionStorage.setItem('purchase_tracked', 'true');
// }
// }
// });
document.addEventListener('DOMContentLoaded', function() {
fbq('track', 'Purchase', {
value: 0.00,
currency: 'USD'
});
});
</script>
<?php
}
// 3. Событие AddPaymentInfo (Добавление платёжной информации)
// На странице https://cosmopet.ae/checkout, но не order-received
if (strpos($_SERVER['REQUEST_URI'], '/checkout') !== false && strpos($_SERVER['REQUEST_URI'], '/order-received') === false) {
?>
<script>
document.addEventListener('DOMContentLoaded', function() {
fbq('track', 'AddPaymentInfo');
});
</script>
<?php
}
}
if (function_exists('acf_add_options_page')) {
acf_add_options_page(array(
'page_title' => 'Site options', // Заголовок страницы в админке
'menu_title' => 'Site options', // Название в меню админки
'menu_slug' => 'site-general-settings', // Уникальный slug для страницы
'capability' => 'edit_posts', // Права доступа (кто может редактировать)
'redirect' => false, // Отключить редирект на дочерние страницы
'post_id' => 'options', // Указывает, что данные сохраняются глобально
'autoload' => false, // Не загружать данные автоматически при старте WP
));
}