(☞ຈل͜ຈ)☞ Главная  Статьи  Загрузчик Домой

Ok!
Ok!
128
$current_time = strtotime("now");
$sunrise = strtotime("09:00");
$sunset = strtotime("21:00");
if ($current_time > $sunrise && $current_time < $sunset && date('w') > 0 && date('w') < 6)
{
	?><a href="https://wa.me/<?=(mob_detect())?"+":""?>74951233121" target="_blank" class="chat_social_item chat_social_wh"></a><?
          }
          else
          {
              ?><div style="display: none" id="wa_wi" data-info="<?=$current_time . ' ' . $sunrise . ' ' . $sunset?>">С 09:00 до 21:00</div><?
          }
whatsupp5600whatsupp widget
32
function find_closed() {
    var tr = $('tr');
    if($('#searchfield').val() != "") {
        for (var i = 0; i < tr.length; i++) {
            if (tr.eq(i).text().toLowerCase().indexOf($('#searchfield').val().toLowerCase()) > -1) {
                tr.eq(i).addClass('opened');
                /*tr.eq(i).css({'background': '#A8E9FF'});*/
                var found = 1;
            }else{
				tr.eq(i).removeClass('opened');
			}
            
        }
		if (found < 1) {
                $('.not-found').text('Не найдено')
            }
    }
}
javascript, поиск в таблице5400JS функция ищет соответствие в словах скрытых строк таблицы. Если найдет — открывает строку, нет — закрывает
50
<script>
jQuery('.order-form-submit').click(function send_order(){
gtag('event', 'purchase', {
  "transaction_id": <?=rand(1,1000)?>,
  "affiliation": "La Maree Buy",
  "value": {TOVAR_SUM},
  "currency": "RUR",
  "tax": 1.18,
  "shipping": 350,
  "items": <?=json_encode( $GLOBALS['item'], JSON_UNESCAPED_UNICODE ); ?>
});
});
</script>
gtag, js, аналитика, purchase4899Скрипт добавки товара в Аналитику gtag js
41
RewriteEngine On 
RewriteCond %{HTTPS} off 
RewriteCond %{HTTP_HOST} ^(?:www.)?(.*)$ [NC]
RewriteRule (.*) https://%1%{REQUEST_URI} [L,R=301]
redirect, редирект3500Редирект с http на https + с www на non-www
121
img.svg {
    clip-path: inset(0px 11px 0px 11px);
}
clip-path3460Обрезка картинок
106
window.i = 1;
setInterval(function( ){
$.ajax({
            type: 'get',
            url: 'https://shop.lamaree.ru/agree/letter.php?iter=' + window.i + '&pass=q12345Q&test=1',
            data: '',
            dataType: "html",
            success: function (data) {
                console.log(window.i);
            }
        });
++window.i;
},1000)
рассылка, скрипт, ajax3450Скрипт рассылки раз в секунду для консоли
150
function find_wrap($string, $search){
    $out = "";
    $pos = 0;
    if(strpos(" " . $string, $search) > 0){
        $in = str_replace($search, "<b>".$search."</b>", strip_tags($string));
        $wordToFind = $search;
        $numWordsBefore = 3;
        $numWordsAfter = 10;


        $words = preg_split('/s+/', $in);
        $found_words    =   preg_grep("/^".$wordToFind.".*/", $words);
        $found_pos      =   array_keys($found_words);
        if(count($found_pos))
        {
            $pos = $found_pos[0];
        }
        if (isset($pos)) {
            $start = ($pos - $numWordsBefore > 0) ? $pos - $numWordsBefore : 0;
            $length = (($pos + ($numWordsAfter + 1) < count($words)) ? $pos + ($numWordsAfter + 1) : count($words) - 1) - $start;
            $slice = array_slice($words, $start, $length);
            $pre_start  =   ($start > 0) ? "...":"";
            $post_end   =   ($pos + ($numWordsAfter + 1) < count($words)) ? "...":"";
            $out = $pre_start.implode(' ', $slice).$post_end;
        }
    }
    return $out;
}
wrap, фраза текста, поиск3400Возвращает искомое слово из текста плюс 3 слова до и 10 слов после
168
add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );

function custom_override_checkout_fields( $fields ) {
    //unset($fields['billing']['billing_first_name']);// имя
    unset($fields['billing']['billing_last_name']);// фамилия
    unset($fields['billing']['billing_company']); // компания
    unset($fields['billing']['billing_address_1']);//
    unset($fields['billing']['billing_address_2']);//
    unset($fields['billing']['billing_city']);
    unset($fields['billing']['billing_postcode']);
    unset($fields['billing']['billing_country']);
    unset($fields['billing']['billing_state']);
    //unset($fields['billing']['billing_phone']);
    //unset($fields['order']['order_comments']);
    //unset($fields['billing']['billing_email']);
    //unset($fields['account']['account_username']);
    //unset($fields['account']['account_password']);
    //unset($fields['account']['account_password-2']);


    unset($fields['billing']['billing_company']);// компания
    unset($fields['billing']['billing_postcode']);// индекс
    return $fields;
}
woocommerce, лишние поля3400Удалить лишние поля для оформления заказа на woocommerce
93
<?=($this->GetFolder().'/images/ .... ?>
картинка шаблона инфоблока3200Путь картинки из папки images размещенной в шаблоне компонента
45
<?
$str = "1234567890";
echo TruncateText($str, 7);
// результатом будет строка "1234567..."
?>
bitrix, truncate, text, truncate text3100Обрезка текста в Битрикс
247
function loadImages(block) {
  Array.from(block.querySelectorAll('img[data-src]')).forEach(function (img, i) {
    let _img = new Image,
        _src = img.getAttribute('data-src');
    let wrap = img.closest('.is-loader');
    _img.onload = function () {
      img.src = _src;
      img.classList.add('is-loaded');
      if (wrap.length > 0) wrap.classList.remove('is-loader');
    }
    if (img.src !== _src) _img.src = _src;
  });
}
изображения, загрузка, load, js3000Загрузка картинок с атрибутом data-src
99
DELETE t1 FROM contacts t1
        INNER JOIN
    contacts t2 
WHERE
    t1.id < t2.id AND t1.email = t2.email;
удалить, mysql, дупликаты2900Удалить дублирующиеся строки базы
62
count(preg_grep('~^[0-9]$~', str_split($str)))
считать сколько цифр, php цифр, count digits2390Посчитать число цифр в строке php
29
@media all and (min-width: 1001px) {
  #sidebar ul li a:after {
    content: " (" attr(data-email) ")";
    font-size: 11px;
    font-style: italic;
    color: #666;
  }
}
media, content2360Текст тега из атрибуте data-*
127
if (strlen($hip) > 120) {
        $pos = 160;
        $crop = $hip;
        if (strlen($crop) > 160) {
            $pos = strpos($hip, ".", 120) + 1;
        }
        $lip = substr($hip, 0, $pos);
}
обрезать, по точке, crop name2360Обрезать описание до точки если оно длиннее 120 знаков
44
@supports (-webkit-overflow-scrolling: touch) {}
iPhone, стили для Apple, стили для iPhone2300Добавить стили ТОЛЬКО для iPhone, так как он единственный поддерживает owerflow-scrolling
79
<?if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)die();
$widthPreview = 300;
$heightPreview = 200;
$widthPreviewBig = 300*2;
$heightPreviewBig = 200*2;
foreach($arResult['ITEMS'] as $i => $arItem) {

        $file = CFile::ResizeImageGet($arItem['FIELDS']["DETAIL_PICTURE"]['ID'], array('width' => $widthPreviewBig, 'height' => $heightPreviewBig), BX_RESIZE_IMAGE_EXACT, true);
        $arResult['ITEMS'][$i]["FIELDS"]["DETAIL_PICTURE"]["SRC"] = $file["src"];
        $arResult['ITEMS'][$i]["FIELDS"]["DETAIL_PICTURE"]["WIDTH"] = $file["width"];
        $arResult['ITEMS'][$i]["FIELDS"]["DETAIL_PICTURE"]["HEIGHT"] = $file["height"];

        $file = CFile::ResizeImageGet($arItem["PREVIEW_PICTURE"]['ID'], array('width' => $widthPreview, 'height' => $heightPreview), BX_RESIZE_IMAGE_EXACT, true);
        $arResult['ITEMS'][$i]["PREVIEW_PICTURE"]["SRC"] = $file["src"];
        $arResult['ITEMS'][$i]["PREVIEW_PICTURE"]["WIDTH"] = $file["width"];
        $arResult['ITEMS'][$i]["PREVIEW_PICTURE"]["HEIGHT"] = $file["height"];
}
resizeImageGet, resize, bitrix2300Ресайз
130
$fr = fopen("log_site_users.txt", "w+");
fwrite($fr, $result . "
");
fclose($fr);
fwrite, запись в файл2300Запись лога в файл php
250
<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(
    PDO::ATTR_PERSISTENT => true
));
?>
pdo, php, mysql, постоянное соединение2200Настройка постоянного соединения с MySQL
139
<div class="itogo">Итого: <?=$pos?> <?=(in_array($pos % 10, array(2, 3, 4)) && $pos < 10 ) ? "позиции" : ($pos == 1 ? "позиция" : "позиций")?></div>
10 позиций2090Множественное по-русски позиций
1 2 3 4 5 6 7 8 9 10 11 12 13 14