Ответы в темах

Просмотр 1 ответа (всего 1)
  • Всё что добавлял это только в function.php дочерней темы.
    Вот его состав:

    <?php
    // Exit if accessed directly
    if ( !defined( 'ABSPATH' ) ) exit;
    
    // BEGIN ENQUEUE PARENT ACTION
    // AUTO GENERATED - Do not modify or remove comment markers above or below:
    
    if ( !function_exists( 'chld_thm_cfg_locale_css' ) ):
        function chld_thm_cfg_locale_css( $uri ){
            if ( empty( $uri ) && is_rtl() && file_exists( get_template_directory() . '/rtl.css' ) )
                $uri = get_template_directory_uri() . '/rtl.css';
            return $uri;
        }
    endif;
    add_filter( 'locale_stylesheet_uri', 'chld_thm_cfg_locale_css' );
             
    if ( !function_exists( 'child_theme_configurator_css' ) ):
        function child_theme_configurator_css() {
            wp_enqueue_style( 'chld_thm_cfg_child', trailingslashit( get_stylesheet_directory_uri() ) . 'style.css', array( 'ct-main-styles','ct-woocommerce-styles' ) );
        }
    endif;
    add_action( 'wp_enqueue_scripts', 'child_theme_configurator_css', 10 );
    
    add_action( 'wp_enqueue_scripts', function () {
    	wp_enqueue_style('blocksy-child-style', get_stylesheet_uri());
    });
    
    // END ENQUEUE PARENT ACTION
    
    add_filter( 'mod_rewrite_rules', 'filter_function_name_3358' );
    function filter_function_name_3358( $rules ){
    	
    	$https = "\n";
    	$https .= "<IfModule mod_rewrite.c>\n";
    	#$https .= "RewriteEngine On\n";
    	$https .= "RewriteRule . - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]\n";
    	#$https .= "RewriteBase /";
    	#$https .= "RewriteRule ^index\.php$ - [L]";
    	#$https .= "RewriteCond %{REQUEST_FILENAME} !-f";
    	#$https .= "RewriteCond %{REQUEST_FILENAME} !-d";
    	#$https .= "RewriteRule . /index.php [L]";
    	$https .= "</IfModule>\n";
    	$https .= "\n";
    
    	return $https . $rules;
    }
    
    //remove_action('woocommerce_after_single_product_summary', 'woocommerce_output_product_data_tabs', 10);
    //remove_action('woocommerce_single_product_summary', 'woocommerce_output_product_data_tabs', 1);
    remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_title', 5);
    remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_price', 10);
    remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_excerpt', 20);
    
    add_filter( 'woocommerce_checkout_fields', 'truephone_required_fields', 25 );
     
    function truephone_required_fields( $fields ) {
     
    	$fields[ 'billing' ][ 'billing_phone' ][ 'required' ] = true; // обязательно 
    	
    	return $fields;
     
    }
    
    function art_shipping_method_notice( $desc = '' ) {
    
    	if ( empty( $desc ) ) {
    		return;
    	}
    	?>
    	<style>
    		.order-notice {
    			padding: 20px 20px;
    			border: none;
    			margin-bottom: 30px;
    			text-align: center;
    			font-size: 18px;
    			font-weight: 500;
    			color: #fff;
    			position: fixed;
    			bottom: 0;
    			z-index: 100000;
    			background-color: #0183C3;
    			box-shadow: -10px -10px 30px 4px rgba(0, 0, 0, 0.1), 10px 10px 30px 4px rgba(45, 78, 255, 0.15);
    			width: 100%;
    			max-width: 1000px;
    			left: 50%;
    			transform: translateX(-50%) translateY(-50%);
    		}
    	</style>
    	<div class="order-notice">
    		<?php echo $desc; ?>
    	</div>
    	<?php
    
    }
    
    add_action( 'woocommerce_after_shipping_rate', 'art_action_after_shipping_rate', 20, 2 );
    
    /**
     * @snippet       Функция вывода сообщения для выбранного метода доставки
     * @sourcecode    https://wpruse.ru/?p=4114
     * @testedwith    WooCommerce 3.9
     *
     * @param  object $method объект метода доставки
     * @param  int    $index  счетчик
     *
     * @author        Artem Abramovich
     */
    function art_action_after_shipping_rate( $method, $index ) {
    
    	// Переменная для сообщения
    	$notice = '';
    
    	// Если корзина, то ничего не выводим
    	if ( is_cart() ) {
    		return;
    	}
    
    	// Получаем выбранный метод
    	$chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
    
    	if ( 'local_pickup:2' === $chosen_methods[0] && 'local_pickup:2' === $method->id  ) {
    		// Сообщение для конкретного способа доставки
    		$notice = 'Внимание! Самовывоз доступен по субботам с 11 до 14 часов';
    
    		// Вывод сообщения. 
    		art_shipping_method_notice( $notice );
    
    	}
    
    }
    
    function truemisha_fio_field( $fields ) { 
    	
    	$fields[ 'billing' ][ 'billing_first_name' ][ 'label' ] = 'Имя получателя';
    	$fields[ 'billing' ][ 'billing_last_name' ][ 'label' ] = 'Фамилия получателя';
    	$fields[ 'billing' ][ 'billing_address_1' ][ 'label' ] = 'Адрес, куда придёт извещение о прибытии посылки в отделение Почты';
    	$fields[ 'billing' ][ 'billing_email' ][ 'label' ] = 'Email. Отправим вам письмо со списком заказа — проверяйте, пожалуйста, папку «Спам».';
     
    	return $fields;
     
    }
    
    add_filter('woocommerce_default_address_fields', 'override_address_fields');
    function override_address_fields( $address_fields ) {
    $address_fields['address_1']['placeholder'] = 'Укажите улицу, номер дома и квартиры. Пример: Мира, 16-22';
    return $address_fields;
    }
    
    //Обязательное указание номера дома в поле Адрес
    add_action('woocommerce_checkout_process', 'address_field_validation', 10, 0);
    function address_field_validation() {
    	
    
        // The field value to check
        $post_value = $_POST['billing_address_1'];
    
        // If there is no number in this field value, stops the checkout process
        // and displays an error message.
        if ( $post_value && ! preg_match( '/[0-9]+/', $post_value ) ) {
    
            // The error message
            throw new Exception( sprintf( __( 'В поле адрес обязательно указать номер дома и квартиры', 'woocommerce' ) ) );
        }
    }
    
    //Меняю адрес для кнопки Вернуться в магазин
    function wc_empty_cart_redirect_url() {
    	return 'https://shop.al-anon.org.ru/';
    }
    add_filter( 'woocommerce_return_to_shop_redirect', 'wc_empty_cart_redirect_url' );
    
    //Устанавливаем минимальную сумму заказа
    add_action( 'woocommerce_checkout_process', 'checkout_min_order_amount' );
     
    function checkout_min_order_amount() {
     
    	$minimum_amount = 700;
     
    	if ( WC()->cart->subtotal < $minimum_amount ) {
     
    		wc_add_notice( 
    			sprintf( 
    				'Минимальная сумма заказа %s, а у вы хотите заказать всего лишь на %s.',
    				wc_price( $minimum_amount ),
    				wc_price( WC()->cart->subtotal )
    			),
    			'error'
    		);
     
    	}
     
    }
    
    /*Динамическа цена от количества*/
    
    add_action( 'woocommerce_before_calculate_totals', 'truemisha_quantity_based_price' );
     
    function truemisha_quantity_based_price( $cart_object ) {
     
     	// вообще всегда можно сделать print_r( $cart_object ); exit; если что-то не ясно
     
    	$product_id = 158701; // целевой ID товара с динамической ценой
     
    	// тут необязательно крутить foreach, но я вот решил сделать так
    	foreach ( $cart_object->get_cart() as $cart_id => $cart_item ) {
     
    		if( $cart_item[ 'product_id' ] == $product_id ) {
    			$quantity = $cart_item[ 'quantity' ];
    			break;
    		}
     
    	}
     
    	// если количество товара больше трёх, можно задать любое своё значение
    	if( ! empty( $quantity ) && $quantity > 5 ) {
     
    		// опять цикл, да
    		foreach ( $cart_object->get_cart() as $cart_id => $cart_item ) {
     
    			// если нужный товар
    			if( $cart_item['product_id'] == $product_id ) {
     
    				// я решил сделать скидку 50%
    				$newprice = $cart_item['data']->get_regular_price() / 1;
     
    				$cart_item['data']->set_price( $newprice );
     
    			}
     
    		}
    	}
     
    }
    
    /*Добавляю дополнительное поле для кнопки Скачать*/
    /*
     * Добавляем поля
     */
    add_action( 'woocommerce_product_options_general_product_data', 'demolink_woo_add_custom_fields' );
    function demolink_woo_add_custom_fields() {
    	echo '<div class="options_group">';// Группировка полей
    	
    	// текстовое поле
    	woocommerce_wp_text_input( array(
    		'id'          => '_demo_name',
    		'label'       => __( 'Надпись на кнопке', 'woocommerce' ),
    		'placeholder' => 'Надпись',
    		'desc_tip'    => 'true',
    		'description' => __( 'Укажите надпись', 'woocommerce' ),
    	) );
    	
    	// текстовое поле
    	woocommerce_wp_text_input( array(
    		'id'          => '_demo_link',
    		'label'       => __( 'Ссылка на демо', 'woocommerce' ),
    		'placeholder' => 'Ссылка',
    		'desc_tip'    => 'true',
    		'data_type'   => 'url',
    		'description' => __( 'Введите ссылку', 'woocommerce' ),
    	) );
    	
    	echo '</div>';
    	
    }
    
    /*
     * Сохраняем значение полей
     */
    add_action( 'woocommerce_process_product_meta', 'demolink_woo_custom_fields_save', 10 );
    function demolink_woo_custom_fields_save( $post_id ) {
    	
    	update_post_meta( $post_id, '_demo_link', esc_url( $_POST['_demo_link'] ) );
    	update_post_meta( $post_id, '_demo_name', esc_attr( $_POST['_demo_name'] ) );
    	
    }
    
    /*Выводим поля*/
    
    add_action( 'woocommerce_before_add_to_cart_form', 'demolink_get_button' );
    function demolink_get_button() {
    	global $post, $product;
    	$demo_link = get_post_meta( $post->ID, '_demo_link', true );
    	$demo_name = get_post_meta( $post->ID, '_demo_name', true );
    	
    	if ( $demo_link ) {
    		$demo_btn = '<div class="demo-link">';
    		$demo_btn .= '<a href="' . $demo_link . '" class="demo-link-button button alt" target="_blank">' . $demo_name . '</a>';
    		$demo_btn .= '</div>';
    		echo $demo_btn;
    	}
    	
    }
    
    //Переименовать поля оформления заказа
    add_filter( 'woocommerce_checkout_fields', 'truemisha_fio_field', 25 );
     
    // Переименовываю слово Доставка
    add_filter( 'woocommerce_shipping_package_name', 'custom_shipping_package_name' );
    function custom_shipping_package_name( $name ) {
      return 'Доставка до отделения Почты<br>будет бесплатной при заказе от 5000 рублей';
    }
    
    //Общий вес в корзине
    add_action('woocommerce_before_checkout_form', 'bbloomer_print_cart_weight');
     
    function bbloomer_print_cart_weight( $posted ) {
    global $woocommerce;
    $notice = 'Вес посылки: ' . $woocommerce->cart->cart_contents_weight . get_option('woocommerce_weight_unit');
    if( is_cart() ) {
        wc_print_notice( $notice, 'notice' );
    } else {
        wc_add_notice( $notice, 'notice' );
    }
    }
    
    //Меня текст Адрес в оформлении заказа
    add_filter('gettext', 'translate_text');
    add_filter('ngettext', 'translate_text');
     
    function translate_text($translated) {
    $translated = str_ireplace('Адрес', 'Адрес, куда придёт извещение о прибытии посылки в отделение Почты', $translated);
    return $translated;
    }
    • Ответ изменён 2 года, 7 месяцев назад пользователем samflynn.
Просмотр 1 ответа (всего 1)