Полезные коды и скрипты для Вордпресс

На этой странице выкладываются скрипты, сниппеты и просто какой то код для Вордпресс, не требующий никакого описания.

1. Добавление произвольного слага в url адрес

Понадобится может например для того что бы переключаться между языками (мультисайт) и оставаться на той же странице но на другом сайте. Код вставляем перед закрывающимся тегом head.

1
2
<?php $slug = basename(get_permalink());
$homeurl = home_url(); ?>
1
2
3
<a href="<?php 
if ( is_front_page() ) echo "/ru";
else echo "$homeurl/ru/$slug"; ?>">ru</a>

2. Вывести содержание или действие только для главной

1
2
3
4
5
6
7
<?php
if (is_front_page() ) {
   echo('This is a homepage'); // действие для главной страницы
} else {
   echo('This is not a homepage'); // действие для не главной страницы
}
?>

3. Перевести не переводимые фразы woocommerce))

1
2
3
4
5
6
add_filter('gettext', 'translate_text');
add_filter('ngettext', 'translate_text');
function translate_text($translated) {
$translated = str_ireplace('The phrase', 'Перевод фразы', $translated);
return $translated;
}

4. Убираем лишние поля в woocomerce

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
add_filter('woocommerce_checkout_fields','remove_checkout_fields');
function remove_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']);
    return $fields;
}

5. Убираем ссылку jqery

1
2
3
4
5
<script type="text/javascript">
$(function(){
$('a.empty-wpmenucart-visible').click( function(){return false});
});
</script>

6. Убрать вторую цену у вариативного товара woocommerce

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
add_filter( 'woocommerce_variable_sale_price_html', 'wc_wc20_variation_price_format', 10, 2 );
 
add_filter( 'woocommerce_variable_price_html', 'wc_wc20_variation_price_format', 10, 2 );
 
function wc_wc20_variation_price_format( $price, $product ) {
 
// ???? ???
 
$prices = array( $product->get_variation_price( 'min', true ), $product->get_variation_price( 'max', true ) );
 
$price = $prices[0] !== $prices[1] ? sprintf( __( '%1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] );
 
// ?? ? ????
 
$prices = array( $product->get_variation_regular_price( 'min', true ), $product->get_variation_regular_price( 'max', true ) );
 
sort( $prices );
 
$saleprice = $prices[0] !== $prices[1] ? sprintf( __( '%1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] );
if ( $price !== $saleprice ) {
 
$price = '<del>' . $saleprice . '</del> <ins>' . $price . '</ins>';
 
}
 
return $price;
 
}

 

7. Добавление стиля css с помощью jquery

1
2
3
4
5
<script type="text/javascript">
$(document).ready(function(){
	$( "div" ).css( 'display', 'block' );
});
</script>

8. Отключение стандартного lightbox (лайтбокса) woocommerce

1
remove_theme_support( 'wc-product-gallery-lightbox' );

Если используется дочерняя тема, нужен больший приоритет

1
2
3
add_action( 'after_setup_theme', function() {
	remove_theme_support( 'wc-product-gallery-lightbox' );
}, 20 );

9. Отключение zoom wordpress

1
remove_theme_support( 'wc-product-gallery-zoom' );

Если используется дочерняя тема, нужен больший приоритет

1
2
3
add_action( 'after_setup_theme', function() {
	remove_theme_support( 'wc-product-gallery-zoom' );
}, 20 );

10. Удалить ссылку jquery

1
2
3
4
5
<script type="text/javascript">
$(function(){
$('a.class').click( function(){return false});
});
</script>

11. Анализ памяти и запросов

1
2
3
4
5
6
7
8
<?php
    echo '<div style="text-align: center;position: absolute;top: 40px;right: 190px;color: #FFFFFF;">
    Анализ сайта: '
        . round(memory_get_usage()/1024/1024, 2) . 'MB '
        .' |  MySQL:' . get_num_queries() . ' | ';
    timer_stop(1);
    echo 'sec</div>';
?>

12. Вывод нужного текста в зависимости от выбора чекбокса

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<script type="text/javascript"> 
function showtext() { 
    var e1=document.getElementById("div1"); 
    var e2=document.getElementById("div2"); 
    var ec=document.getElementById("check"); 
 
    if (ec.checked) { 
            e1.style.display='none'; 
            e2.style.display=''; 
    } else 
    { 
            e1.style.display='block'; 
            e2.style.display=''; 
    } 
} 
</script>

 

1
2
3
4
5
<body> 
<input id="check" type="checkbox" name="rem" onchange="javascript:showtext();"> 
<p id="div1">Текст 1</p>
<p id="div2" style="display:none">Текст 2</p> 
</body>

13. Всплывающее окно с cookies

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<!-- Модальное Окно  -->
<div id="overlay-cook">
  <div class="popup">
    <p>текст</p>
    <button id="hide_popup" class="dont-show-me">больше не показывать</button>
  </div>
</div>
<style type="text/css">#overlay-cook{position: fixed;bottom: 0;width: 100%;text-align: center;background: rgb(221, 231, 255);padding: 20px 0;}</style>
<script type="text/javascript">
    function getCookie(name) {
        let cookie_arr = document.cookie.split('; ');
        let cookie_obj = {};
 
        for (let i=0; i<cookie_arr.length; i++) {
            let nv = cookie_arr[i].split('=');
            cookie_obj[nv[0]] = nv[1]; 
        }
 
        return cookie_obj[name];
    }        
 
    let overlay_div = document.getElementById('overlay');
 
    if ( getCookie('hide_popup') == 'yes' ) {
        overlay_div.style.display='none';
    }
 
    // При нажатии на кнопку ставим cookie, которая будет запрещать показ
    // модального окна
    document.getElementById('hide_popup')
        .addEventListener('click', function() { 
            // Ставим cookie на минуту.                
            var date = new Date(new Date().getTime() + 60 * 1000);
            document.cookie = "hide_popup=yes; path=/; expires=" + date.toUTCString();
 
            // и сразу же скрываем окно
            overlay_div.style.display='none';
        });
</script>

 

14. Скрываем визуальный редактор

1
2
3
4
5
6
7
8
9
10
11
12
<?php
add_action( 'init', 'hide_editor' );
function hide_editor() {
$post_id = ''; $template = '';
if(isset($_GET['post'])){
  $post_id = $_GET['post'];
  $template = get_post_meta($post_id, '_wp_page_template', true);
}
if($template == 'index.php'){
    remove_post_type_support( 'page', 'editor' );
}}
?>

15. Отключаем редактор плагинов и тем в админке WordPress

В wp-config.php добавляем

1
define('DISALLOW_FILE_EDIT', true);

16. Убираем возможность деактивации плагинов

В functions.php добавляем

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//удаляем кнопки изменить и деактивировать у плагинов start
function wph_banplug($actions, $plugin_file, $plugin_data, $context) {
    if (array_key_exists('edit', $actions))
    unset($actions['edit']);
     if (array_key_exists('deactivate', $actions) && 
	 in_array($plugin_file, array(
             'advanced-custom-fields-pro/acf.php',
             'wp-translitera/wp-translitera.php'
     )))
    unset($actions['deactivate']);
    return $actions;
}
add_filter('plugin_action_links', 'wph_banplug', 10, 4);
//удаляем кнопки изменить и деактивировать у плагинов end

17. Убираем возможность обновления плагинов

1
2
3
4
5
6
7
8
//отключение обновления плагинов start
function disable_updates($value) {
   unset($value->response['akismet/akismet.php']);
   unset($value->response['all-in-one-seo-pack/all_in_one_seo_pack.php']);
   return $value;
}
add_filter('site_transient_update_plugins', 'disable_updates');
//отключение обновления плагинов end

18. Закрыть доступ к сайту для всех, кроме определенного IP

1
2
3
order deny,allow 
deny from all 
allow from xxx.xxx.xxx.xxx

19. Определение типа устройства

1
2
3
4
5
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
	// код для мобильных устройств
} else {
	// код для обычных устройств
}

20. Определение разрешения jqeury

1
2
3
4
5
6
7
8
9
10
$(window).resize(function () {
 
    if($(window).width() < 769){
 
	$('div').attr('name_attr', 'text');
 
		}	else { 
	$('div').attr('name_attr', 'number');
    }
});

 

21. Плавная прокрутка к якорю с отступом

1
2
3
4
5
6
7
8
$(document).ready(function(){
    $("body").on("click","a", function (event) {
        event.preventDefault();
        var id  = $(this).attr('href'),
            top = $(id).offset().top;
        $('body,html').animate({scrollTop: top - ($('h3,h2').height()+ 1)}, 1500);
    });
});
Добавить комментарий