Skip to content

Instantly share code, notes, and snippets.

@mksddn
Last active September 30, 2024 14:46
Show Gist options
  • Select an option

  • Save mksddn/2570b629b0b48ee141a5e021105ae1d1 to your computer and use it in GitHub Desktop.

Select an option

Save mksddn/2570b629b0b48ee141a5e021105ae1d1 to your computer and use it in GitHub Desktop.
------ Права доступа к файлам и папкам ------
Все файлы должны быть 664.
Все папки должны быть 775.
wp-config.php должен быть 660.
------------ STYLE.CSS ------------
/*
Theme Name: Twenty Seventeen
Author: web-makster.ru
Author URI: http://web-makster.ru;
Version: 1.0
*/
--------- Шаблон страницы ---------
<?php
/*
Template Name: Мой шаблон страницы
*/
?>
-------- Переезд сайта (через файл wp-config.php) --------
<?php update_option('siteurl', 'https://newsite.ru');
update_option('home', 'https://newsite.ru'); ?>
-------- SQL запросы для смены url --------
UPDATE wp_options SET option_value = REPLACE(option_value, 'http://old-site.ru', 'https://new-site') WHERE option_name = 'home' OR option_name = 'siteurl';
UPDATE wp_posts SET post_content = REPLACE (post_content, 'http://old-site.ru', 'https://new-site');
UPDATE wp_postmeta SET meta_value = REPLACE (meta_value, 'http://old-site.ru','https://new-site');
------------ ЧАСТО ИСПОЛЬЗУЕМЫЙ КОД ------------
Выводим содержимое конкретной страницы
<?php $post = get_page(7);
$content = $post->post_content;
echo apply_filters('the_content', $content); ?>
Выводим содержимое записи или страницы
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<h2><?php the_title(); ?></h2>
<?php the_excerpt(); ?>
<?php the_content(); ?>
<?php endwhile;
else : ?>
<p>Извините, ничего не найдено.</p>
<?php endif; ?>
Вставить кусок кода
<?php get_template_part('inc/recommend'); ?>
Красивые номера телефонов
<a href="tel:<?php $phone = get_post_meta(10, 'contact-tel', true);
$phone = preg_replace("#[^\d]#", "", $phone);
$phone = substr($phone, 1);
echo preg_replace('/^(\d{3})(\d{3})(\d{2})(\d{2})$/iu', '+7$1$2$3$4', $phone); ?>"><?php echo get_post_meta(10, 'contact-tel', 1); ?></a>
------------- FUNCTIONS.PHP ---------------
<?php
function THEMENAME_setup()
{
add_theme_support('automatic-feed-links');
add_theme_support('title-tag');
add_theme_support('post-thumbnails');
add_theme_support('html5', array(
'search-form',
'comment-form',
'comment-list',
'gallery',
'caption',
// 'style',
// 'script',
));
add_theme_support('custom-logo');
}
add_action('after_setup_theme', 'THEMENAME_setup');
register_nav_menus(array(
'main_menu' => esc_html__('Основное меню'),
'footer_menu' => esc_html__('Нижнее меню'),
));
// Регистрируем новые размеры изображений
if (function_exists('add_image_size')) {
// 300 в ширину и без ограничения в высоту
add_image_size('category-thumb', 300, 9999);
// Кадрирование изображения
add_image_size('homepage-thumb', 220, 180, true);
}
## отключаем создание миниатюр файлов для указанных размеров
add_filter('intermediate_image_sizes', 'delete_intermediate_image_sizes');
function delete_intermediate_image_sizes($sizes)
{
// размеры которые нужно удалить
return array_diff($sizes, [
'thumbnail',
'medium_large',
'large',
'1536x1536',
'2048x2048',
]);
}
// Правильно добавляем файл CSS стилей
function child_enqueue_styles()
{
wp_enqueue_style('novomed-child-theme-css', get_stylesheet_directory_uri() . '/style.css', array('astra-theme-css'), CHILD_THEME_NOVOMED_CHILD_VERSION, 'all');
}
add_action('wp_enqueue_scripts', 'child_enqueue_styles', 15);
// Подключаем нужные скрипты как модули
function add_type_attribute($tag, $handle, $src)
{
if ('slug-of-module-script-file' !== $handle) {
return $tag;
}
$tag = '<script type="module" src="' . esc_url($src) . '"></script>';
return $tag;
}
add_filter('script_loader_tag', 'add_type_attribute', 10, 3);
// Поддержка SVG
function add_file_types_to_uploads($file_types)
{
$new_filetypes = array();
$new_filetypes['svg'] =
'image/svg+xml';
$file_types = array_merge(
$file_types,
$new_filetypes
);
return $file_types;
}
add_action('upload_mimes', 'add_file_types_to_uploads');
// Добавить описание (отрывок) к странице
function add_excerpt_page()
{
add_post_type_support('page', 'excerpt');
}
add_action('init', 'add_excerpt_page');
// Отключаем редактор Гутенберг
add_filter('use_block_editor_for_post', '__return_false', 10);
// Удаляет "Рубрика: ", "Метка: " и т.д. из заголовка архива
add_filter('get_the_archive_title', function ($title) {
return preg_replace('~^[^:]+: ~', '', $title);
});
// удаляет H2 из шаблона пагинации
add_filter('navigation_markup_template', 'my_navigation_template', 10, 2);
function my_navigation_template($template, $class)
{
return '
<nav class="navigation %1$s" role="navigation">
<div class="nav-links">%3$s</div>
</nav>
';
}
// Миниатюры к постам
if (!function_exists('AddThumbColumn') && function_exists('add_theme_support')) {
add_theme_support('post-thumbnails', array('post', 'page'));
function AddThumbColumn($cols)
{
$cols['thumbnail'] = __('Thumbnail');
return $cols;
}
function AddThumbValue($column_name, $post_id)
{
$width = (int) 60;
$height = (int) 60;
if ('thumbnail' == $column_name) {
$thumbnail_id = get_post_meta($post_id, '_thumbnail_id', true);
$attachments = get_children(array('post_parent' => $post_id, 'post_type' => 'attachment', 'post_mime_type' => 'image'));
if ($thumbnail_id)
$thumb = wp_get_attachment_image($thumbnail_id, array($width, $height), true);
elseif ($attachments) {
foreach ($attachments as $attachment_id => $attachment) {
$thumb = wp_get_attachment_image($attachment_id, array($width, $height), true);
}
}
if (isset($thumb) && $thumb) {
echo $thumb;
} else {
echo __('None');
}
}
}
add_filter('manage_posts_columns', 'AddThumbColumn');
add_action('manage_posts_custom_column', 'AddThumbValue', 10, 2);
add_filter('manage_pages_columns', 'AddThumbColumn');
add_action('manage_pages_custom_column', 'AddThumbValue', 10, 2);
}
// Отключаем комментарии
add_action('admin_init', function () {
// Redirect any user trying to access comments page
global $pagenow;
if ($pagenow === 'edit-comments.php') {
wp_safe_redirect(admin_url());
exit;
}
// Remove comments metabox from dashboard
remove_meta_box('dashboard_recent_comments', 'dashboard', 'normal');
// Disable support for comments and trackbacks in post types
foreach (get_post_types() as $post_type) {
if (post_type_supports($post_type, 'comments')) {
remove_post_type_support($post_type, 'comments');
remove_post_type_support($post_type, 'trackbacks');
}
}
});
// Close comments on the front-end
add_filter('comments_open', '__return_false', 20, 2);
add_filter('pings_open', '__return_false', 20, 2);
// Hide existing comments
add_filter('comments_array', '__return_empty_array', 10, 2);
// Remove comments page in menu
add_action('admin_menu', function () {
remove_menu_page('edit-comments.php');
});
// Remove comments links from admin bar
add_action('init', function () {
if (is_admin_bar_showing()) {
remove_action('admin_bar_menu', 'wp_admin_bar_comments_menu', 60);
}
});
// Сохраняем UTM в куки
add_action('init', 'save_utm_to_cookie');
function save_utm_to_cookie()
{
$day = 30;
$date = time() + 3600 * 24 * $day;
if (isset($_GET["utm_source"])) setcookie("utm_source", $_GET["utm_source"], $date, "/");
if (isset($_GET["utm_medium"])) setcookie("utm_medium", $_GET["utm_medium"], $date, "/");
if (isset($_GET["utm_campaign"])) setcookie("utm_campaign", $_GET["utm_campaign"], $date, "/");
if (isset($_GET["utm_content"])) setcookie("utm_content", $_GET["utm_content"], $date, "/");
if (isset($_GET["utm_term"])) setcookie("utm_term", $_GET["utm_term"], $date, "/");
}
// Шорткод вывода основного контента в Elementor
if (!is_admin()) {
function wpc_elementor_shortcode($atts)
{
global $post;
$my_postid = $post->ID;
$content_post = get_post($my_postid);
$content = $content_post->post_content;
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]&gt;', $content);
echo $content;
}
add_shortcode('my_elementor_content_output', 'wpc_elementor_shortcode');
}
// ACF внутри AMP
function my_amp_content($content)
{
$actual_link = (empty($_SERVER['HTTPS']) ? 'http' : 'https') . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
if (basename($actual_link) == 'amp' && have_rows('custom_blocks')) {
include 'template-parts/just-collect-css.php';
ob_start();
while (have_rows('custom_blocks')) : the_row();
if (get_row_layout() == 'block_text') :
include 'template-parts/block-text.php';
elseif (get_row_layout() == 'block_contents') :
include 'template-parts/block-contents.php';
endif;
endwhile;
$content .= ob_get_clean();
}
return $content;
}
add_filter('the_content', 'my_amp_content');
// WOOCOMMERCE
// Минимальная сумма заказа
function wc_minimum_order_amount()
{
$minimum = 20000;
if (WC()->cart->total < $minimum) {
if (is_cart()) {
wc_print_notice(
sprintf(
'Текущая сумма заказа %s — Минимальная сумма заказа - %s',
wc_price(WC()->cart->total),
wc_price($minimum)
),
'error'
);
} else {
wc_add_notice(
sprintf(
'Текущая сумма заказа %s — Минимальная сумма заказа - %s',
wc_price(WC()->cart->total),
wc_price($minimum)
),
'error'
);
}
}
}
add_action('woocommerce_checkout_process', 'wc_minimum_order_amount');
add_action('woocommerce_before_cart', 'wc_minimum_order_amount');
// Скидка в зависимости от суммы заказа
function woo_discount_total(WC_Cart $cart)
{
if (is_admin() && !defined('DOING_AJAX')) {
return;
}
$woo_current_price = $cart->subtotal; // Текущая итоговая сумма
if ($woo_current_price >= 30000 && $woo_current_price <= 50000) {
$discount = $cart->subtotal * 0.05; // 0.05 - это 5%
$cart->add_fee('Скидка в 5% за заказ на сумму от 30 000 до 50 000 рублей ', -$discount);
} elseif ($woo_current_price >= 50001 && $woo_current_price <= 70000) {
$discount = $cart->subtotal * 0.1;
$cart->add_fee('Скидка в 10% за заказ на сумму более 50 000 рублей ', -$discount);
} elseif ($woo_current_price >= 70001 && $woo_current_price <= 100000) {
$discount = $cart->subtotal * 0.15;
$cart->add_fee('Скидка в 15% за заказ на сумму более 70 000 рублей ', -$discount);
} elseif ($woo_current_price > 100001) {
$discount = $cart->subtotal * 0.2;
$cart->add_fee('Скидка в 20% за заказ на сумму более 100 000 рублей ', -$discount);
}
}
add_action('woocommerce_cart_calculate_fees', 'woo_discount_total');
// Все товары виртуальные по умолчанию
add_action('woocommerce_product_options_general_product_data', 'enable_virtual_option');
function enable_virtual_option()
{
?>
<script>
(function($) {
$('input[name=_virtual]').prop('checked', true);
})(jQuery);
</script>
<?php
}
// Меняем текст "добавить в корзину"
add_filter('woocommerce_product_single_add_to_cart_text', 'tb_woo_custom_cart_button_text');
add_filter('woocommerce_product_add_to_cart_text', 'tb_woo_custom_cart_button_text');
function tb_woo_custom_cart_button_text()
{
return __('Забронировать', 'woocommerce');
}
// Скрываем ненужные поля при оформлении заказа
add_filter('woocommerce_checkout_fields', 'wpbl_remove_some_fields', 9999);
function wpbl_remove_some_fields($array)
{
//unset( $array['billing']['billing_first_name'] ); // Имя
//unset( $array['billing']['billing_last_name'] ); // Фамилия
//unset( $array['billing']['billing_email'] ); // Email
//unset( $array['order']['order_comments'] ); // Примечание к заказу
// unset( $array['billing']['billing_phone'] ); // Телефон
unset($array['billing']['billing_company']); // Компания
unset($array['billing']['billing_country']); // Страна
unset($array['billing']['billing_address_1']); // 1-ая строка адреса
unset($array['billing']['billing_address_2']); // 2-ая строка адреса
unset($array['billing']['billing_city']); // Населённый пункт
unset($array['billing']['billing_state']); // Область / район
unset($array['billing']['billing_postcode']); // Почтовый индекс
// Возвращаем обработанный массив
return $array;
}
add_filter('woocommerce_ship_to_different_address_checked', '__return_false');
// Свое сообщение при заказе
add_filter('woocommerce_thankyou_order_received_text', 'woo_my_thankyou_order_received_text');
function woo_my_thankyou_order_received_text()
{
return "Спасибо за ваш заказ!<br>Менеджер перезвонит вам в рабочее время, с понедельника по пятницу, с 9 до 19 часов по Московскому времени.";
}
// убираем стандартные варианты сортировки
function woo_catalog_orderby($orderby)
{
// unset($orderby["price"]); // Сортировка по цене по возрастанию
// unset($orderby["price-desc"]); // Сортировка по цене по убыванию
unset($orderby["popularity"]); // Сортировка по популярности
unset($orderby["rating"]); // Сортировка по рейтингу
unset($orderby["date"]); // Сортировка по дате
unset($orderby["title"]); // Сортировка по названию
unset($orderby["menu_order"]); // Сортировка по умолчанию (можно определить порядок в админ панели)
return $orderby;
}
add_filter("woocommerce_catalog_orderby", "woo_catalog_orderby", 20);
// изначально сортируем по атрибуту
function sort_products_by_brand($q)
{
$terms = get_terms(array('taxonomy' => 'pa_moshhnost', 'fields' => 'ids'));
$tax_query = $q->get('tax_query');
$tax_query[] = array(
'taxonomy' => 'pa_moshhnost',
'field' => 'term_id',
'terms' => $terms,
);
$q->set('tax_query', $tax_query);
$q->set('orderby', 'term_id');
// $q->set( 'order', 'DESC' ); // by default is ASC so uncomment if you want DESC.
}
add_action('woocommerce_product_query', 'sort_products_by_brand');
// изначально сортируем по дате ACF
add_action('pre_get_posts', 'custom_post_count');
function custom_post_count($query)
{
global $wp_the_query;
if ($wp_the_query === $query) {
if (!is_admin()) {
if (('product' == get_post_type() || is_post_type_archive('product') || is_tax('product_cat') || is_product_taxonomy() || is_shop())) :
$expire = get_field('date') ?: date('Ymd');
$query->set('meta_query', [
'relation' => 'OR',
[
'key' => 'date',
'value' => $expire,
'compare' => '>=',
'type' => 'DATE',
],
[
'key' => 'date',
'compare' => 'NOT EXISTS',
],
]);
$query->set('orderby', 'meta_value');
return;
endif;
}
}
return $query;
};
// Добавляем условия в стандартный вывод сортировки WP (выпадающий список)
function woocommerce_catalog_name_orderby($sortby)
{
$sortby['order_by_date'] = 'По дате тура';
return $sortby;
}
add_filter('woocommerce_catalog_orderby', 'woocommerce_catalog_name_orderby', 1);
// Устанавливаем новый тип сортровки по умолчанию
add_filter('woocommerce_default_catalog_orderby', 'custom_default_catalog_orderby');
function custom_default_catalog_orderby()
{
return 'order_by_date'; // Can also use title and price
}
// Gutenberg для товаров
function wphelp_gutenberg_products($can_edit, $post_type)
{
if ($post_type == 'product') {
$can_edit = true;
}
return $can_edit;
}
add_filter('use_block_editor_for_post_type', 'wphelp_gutenberg_products', 10, 2);
// Отключаем выбор количества товара для добавления в корзину
function custom_remove_all_quantity_fields($return, $product)
{
return true;
}
add_filter('woocommerce_is_sold_individually', 'custom_remove_all_quantity_fields', 10, 2);
// Перенаправляем сразу на оформление заказа при добавлении в корзину (нужно отключить перенаправление и ajax в настройках woocommerce)
add_filter('woocommerce_add_to_cart_redirect', 'truemisha_skip_cart');
function truemisha_skip_cart($redirect)
{
return wc_get_checkout_url();
}
// Только один товар в корзине
add_filter('woocommerce_add_cart_item_data', 'woo_custom_add_to_cart');
function woo_custom_add_to_cart($cart_item_data)
{
global $woocommerce;
$woocommerce->cart->empty_cart();
return $cart_item_data;
}
// Меняем текст РАСПРОДАЖА на процент скидки
add_filter('woocommerce_sale_flash', 'my_custom_sale_flash');
function my_custom_sale_flash($text)
{
global $product;
$percentage = round((($product->get_regular_price() - $product->get_sale_price()) / $product->get_regular_price()) * 100);
return '<span class="onsale">- ' . $percentage . '%</span>';
}
// Поиск по артикулу
function search_by_sku($search, &$query_vars)
{
global $wpdb;
if (isset($query_vars->query['s']) && !empty($query_vars->query['s'])) {
$args = array(
'posts_per_page' => -1,
'post_type' => 'product',
'meta_query' => array(
array(
'key' => '_sku',
'value' => $query_vars->query['s'],
'compare' => 'LIKE'
)
)
);
$posts = get_posts($args);
if (empty($posts)) return $search;
$get_post_ids = array();
foreach ($posts as $post) {
$get_post_ids[] = $post->ID;
}
if (sizeof($get_post_ids) > 0) {
$search = str_replace('AND (((', "AND ((({$wpdb->posts}.ID IN (" . implode(',', $get_post_ids) . ")) OR (", $search);
}
}
return $search;
}
add_filter('posts_search', 'search_by_sku', 999, 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment