Show regular price in minicart

This code for showing regular price for each product in minicart and subtotal sum. Work with simple and variable products. For bundle products — need corrections.

function display_regular_price_in_mini_cart( $item_data, $cart_item ) {
    
    $product = wc_get_product( $cart_item['product_id'] );
    $quantity = $cart_item['quantity'];
    if ( $product->is_type( 'variable' ) ) {
        $variation_id = $cart_item['variation_id'];
        $variation = wc_get_product( $variation_id );
        $regular_price = $variation->get_regular_price();
    } else {
        $regular_price = $product->get_regular_price();
    }
    
    if ( $regular_price ) {
        $item_data[] = array(
            'key'     => 'regular_price',
            'value'   => '<span class="test_quantity">'.$quantity.' × '.'</span><del>'.wc_price( $regular_price ).'</del><br/>',
            'display' => '',
        );
    }
    
    return $item_data;
}
add_filter( 'woocommerce_get_item_data', 'display_regular_price_in_mini_cart', 10, 2 );

function show_subtotal_with_regular_prices( $subtotal ) {
   
    $cart = WC()->cart->get_cart();
    $subtotal_sale = $subtotal;
    $subtotal = 0;

    foreach ( $cart as $cart_item_key => $cart_item ) {
        $product_id = $cart_item['product_id'];
        $product = wc_get_product( $cart_item['product_id'] );
        $quantity = $cart_item['quantity'];
        if ( $product->is_type( 'variable' ) ) {
        $variation_id = $cart_item['variation_id'];
        $variation = wc_get_product( $variation_id );
        $regular_price = $variation->get_regular_price();
        } else {
            $regular_price = $product->get_regular_price();
        }
            $subtotal += $regular_price * $quantity;
    }
    return  $subtotal_sale.'<del>'.wc_price($subtotal).'</del>';
}

add_filter( 'woocommerce_cart_subtotal', 'show_subtotal_with_regular_prices' );

Import database dump in heidiSQL

Unlike phpmyadmin there is no button in heidiSQL for import.
You need to use ‘Run SQL’ menu item.
HeidiSQL using for import large sql files.

Ubuntu change hostname

If you need to change server hostname

sudo vi /etc/hostname
sudo vi /etc/hosts
sudo restart

In vi editor use Shift+i for insertion mode, Shift+; for command line mode.
For changes saving use wq command, for exit without saving use q! command

After reboot check new hostname with

hostname

Заблокировать бота в nginx

«thesis-research-bot» делает множество обращений в БД и может положить сайт.

для того, чтобы заблокировать доступ этому боту в nginx нужно добавить файл с содержимым

### case insensitive
if ($http_user_agent ~* (thesis-research-bot|"thesis-research-bot")) {
	return 403;
}

в файл .conf в /etc/nginx/vhosts-includes/

Файл может иметь произвольное имя и правила из него подхватываются nginx

После этого необходимо проверить корректность конфигурационных файлов и перезапустить nginx командами

nginx -t
sudo systemctl restart nginx

community.cloudflare.com/t/getting-tons-of-bad-bots-attack-recently/578502

Слияние веток git

Если при слиянии веток есть изменения в одних и тех же файлах проекта, то будет конфликт слияния, который необходимо разрешить вручную.

Для разрешения конфликтов слияния есть различные утилиты. Но суть у всех одна — открываются окна с изменениями файла в разных ветках и пользователь должен вручную выбрать какие изменения он хочет иметь в итоговой версии. Читать далее «Слияние веток git»

Add your custom log to woocommerce

You may use this code to save custom information in wp loop

if (function_exists('wc_get_logger')) {
           $logger = wc_get_logger();
           $context = array( 'source' => 'Log name here'  );
           $logger->info( $err_msg, $context );
}

It will be available in woocommerce Status-> Logs tab

nginx редирект всех страниц, кроме указанных

Для того, чтобы сделать редирект всех страниц одного сайта на такие же адреса на другом сайте, необходимо добавить в конфигурационный файл nginx следующие правила:

location / {
        return 301 https://newsite.com$request_uri;
}

Если же необходимо оставить какие-то из урлов работающими на старом домене, то правило будет выглядеть так:

location ~ ^/(?!(wp-json|wp-admin)) {
   return 301 https://newsite.com$request_uri;
}

 

104: Connection reset by peer

Если при попытке открыть страницу аналитики woocommerce возникает ошибка 502 Bad Gateway, а в логе сервера при этом сообщение

104: Connection reset by peer

То одной из возможных причин может быть конфликт плагинов. Конкретно у меня была проблема с WooCommerce Google Product Feed. После его деактивации страница начинала работать как надо.

Если дело не в этом плагине, то нужно попробовать поочередно отключать их все. Также необходимо в логе смотреть ошибки по php — сама ошибка говорит о том, что nginx не смог получить корректный ответ от php-fpm