Skip to content

Instantly share code, notes, and snippets.

@TolyanDimov
Last active February 13, 2023 04:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TolyanDimov/f6fae93d76e60dd241562d0f499c310e to your computer and use it in GitHub Desktop.
Save TolyanDimov/f6fae93d76e60dd241562d0f499c310e to your computer and use it in GitHub Desktop.
<?php
/**
* Plugin Name: WPMOD
* Description: CPT
* Version: +100500
*/
/**
*
* general
*
* mod_cpt_services() ------------- Услуги
* permalink_services_cat() ------- Структура ссылок для категорий
* rewrite_rules_services_cat() --- Генерация правил перезаписи ссылок для категорий
* reset_rewrite_rules() ---------- Сброс правил перезаписи при создании/удалении/изменении категорий и тегов.
*
* breadcrumbs_cpt_services() ----- Blocksy - добавление 'post_type' в хлебные крошки.
* breadcrumbs_cpt_services_cat() - Blocksy - замена 'taxonomy_name' в хлебных крошках.
*
* permalink_product() ------------ Правила перезаписи ссылок для 'product-category' + обновление новый правил
* permalink_product_cat() -------- Обновление пермалинков при создании новой категории
* permalink_flush() -------------- Замена слага 'product-category' на 'catalog'
*/
//@@@+======================================================
// general
//==========================================================
// add: Чтобы работали шорткоды в описании рубрик
add_filter( 'term_description', 'shortcode_unautop');
add_filter( 'term_description', 'do_shortcode' );
// add: Удаляем svg из html (https://github.com/WordPress/gutenberg/issues/38299#issuecomment-1212422975)
remove_action( 'wp_body_open', 'wp_global_styles_render_svg_filters' );
// add: Отключаем создание миниатюр (https://wordpress.stackexchange.com/questions/91166/how-to-disable-wordpress-from-creating-thumbnails)
add_filter( 'intermediate_image_sizes', '__return_empty_array' );
// add: 301 редирект на канонические ссылки (https://qna.habr.com/q/1251934)
add_action( 'template_redirect', 'redirect_canonical' );
function redirect_canon() {
if ( is_single()) {
global $wp;
$wp->parse_request();
$current_url = trim( home_url( $wp->request ), "/" );
$redirect = get_permalink();
$surl = trim( $redirect, "/" );
if( $current_url != $surl ) {
wp_redirect( $redirect, 301 );
exit;
}
}
}
//@@@+======================================================
// mod_cpt_services()
// Новый тип записи + категории + теги
//==========================================================
add_action( 'init', 'mod_cpt_services', 0 );
function mod_cpt_services() {
// cpt_services
register_post_type( 'cpt_services', array(
'labels' => array(
'name' => 'Услуги',
'singular_name' => 'Услуга',
'menu_name' => 'Услуги',
'name_admin_bar' => 'Услугу',
'add_new' => 'Добавить новую',
'add_new_item' => 'Добавить новую услугу',
'edit_item' => 'Редактироваь услугу',
'new_item' => 'Новая услуга',
'view_item' => 'Показать услугу',
'view_items' => 'Показать услуги',
'search_items' => 'Поиск услуг',
'not_found' => 'Услуг не найдено.',
'not_found_in_trash' => 'В корзине услуг не найдено.',
'parent_item_colon' => 'Родительская услуга:',
'all_items' => 'Все услуги',
'archives' => 'Список услуг',
'attributes' => 'Атрибуты услуги',
'insert_into_item' => 'Вставить на услугу',
'uploaded_to_this_item' => 'Загружено на эту страницу',
'featured_image' => 'IMG',
'set_featured_image' => 'Установить IMG',
'remove_featured_image' => 'Удалить IMG',
'use_featured_image' => 'Использовать IMG',
'filter_items_list' => 'Фильтр списка услуг',
'items_list_navigation' => 'Навигация по списку услуг',
'items_list' => 'Список услуг',
'item_published' => 'Услуга опубликована.',
'item_published_privately' => 'Услуга опубликована в частном порядке.',
'item_reverted_to_draft' => 'Услуга вернулась к черновику.',
'item_scheduled' => 'Услуга запланирована.',
'item_updated' => 'Услуга обновлена.',
),
'public' => true,
'menu_position' => 100,
'has_archive' => true,
'menu_icon' => 'dashicons-category',
'rewrite' => array( 'slug' => 'services', 'with_front' => false ),
'supports' => array(
'title',
'editor',
'author',
'thumbnail',
'excerpt',
'trackbacks',
'custom-fields',
'comments',
'revisions',
'page-attributes',
'post-formats'
),
'query_var' => true,
'show_in_rest' => true,
));
// cpt_services_cat
register_taxonomy( 'cpt_services_cat', array( 'cpt_services' ), array(
'labels' => array(
'name' => 'Категории услуг',
'singular_name' => '', // Remove "Услуга" from H1
'menu_name' => 'Категории услуг',
'search_items' => 'Поиск категории',
'all_items' => 'Все категории',
'parent_item' => 'Родительская категория',
'parent_item_colon' => 'Родительская категория:',
'edit_item' => 'Редактировать категорию',
'view_item' => 'Показать категорию',
'update_item' => 'Обновить категорию',
'add_new_item' => 'Добавить новую категорию',
'new_item_name' => 'Название новой категории',
'not_found' => 'Категорий не найдено.',
'no_terms' => 'Нет категорий',
'items_list_navigation' => 'Навигация по списку категорий',
'items_list' => 'Список категорий',
'most_used' => 'Часто используемые',
'back_to_items' => '&larr; Вернуться к категориям',
),
'public' => true,
'hierarchical' => true,
'rewrite' => array( 'slug' => 'services', 'hierarchical' => true, 'with_front' => false ),
'query_var' => true,
'show_in_rest' => true,
));
// cpt_services_tag
register_taxonomy( 'cpt_services_tag', array( 'cpt_services' ), array(
'labels' => array(
'name' => 'Теги услуг',
'singular_name' => '', // Remove "Тег" from H1
'menu_name' => 'Теги услуг',
'search_items' => 'Поиск тегов',
'popular_items' => 'Популярные теги',
'all_items' => 'Все теги',
'edit_item' => 'Редактировать тег',
'view_item' => 'Показать тег',
'update_item' => 'Обновить тег',
'add_new_item' => 'Добавить новый тег',
'new_item_name' => 'Название нового тега',
'separate_items_with_commas' => 'Раделяйте теги запятыми',
'add_or_remove_items' => 'Добавить или удалить теги',
'choose_from_most_used' => 'Выберите из наиболее часто используемых тегов',
'not_found' => 'Тегов не найдено.',
'no_terms' => 'Нет тегов',
'items_list_navigation' => 'Навигация по списку тегов',
'items_list' => 'Список тегов',
'most_used' => 'Часто используемые',
'back_to_items' => '&larr; Вернуться к тегам',
),
'public' => true,
'hierarchical' => false,
'rewrite' => array( 'slug' => 'services-tag', 'with_front' => false ),
'query_var' => true,
'show_in_rest' => true,
));
// reset_rewrite_rules
flush_rewrite_rules();
}
//==========================================================
// permalink_services_cat()
// Правила перезаписи ссылок для mod_cpt_services()
//==========================================================
add_filter( 'post_type_link', 'permalink_services_cat', 1, 2 );
function permalink_services_cat( $permalink, $post ) {
if ( strpos( $permalink, 'services' ) === false) return $permalink;
$terms = get_the_terms( $post, 'cpt_services_cat' );
if ( !is_wp_error( $terms ) && !empty( $terms ) && is_object( $terms[0] )) {
$taxonomy_slug = get_term_parents_list( $terms[0]->term_id, 'cpt_services_cat', array(
'separator' => '/', 'format' => 'slug', 'link' => false, 'inclusive' => true
));
$taxonomy_slug = trim( $taxonomy_slug, '/' );
}
else {
$taxonomy_slug = 'sandbox';
}
return str_replace( 'services', 'services/' . $taxonomy_slug, $permalink );
}
//==========================================================
// rewrite_rules_services_cat()
// Правила отображения структуры url для mod_cpt_services()
//==========================================================
add_filter( 'generate_rewrite_rules', 'rewrite_rules_services_cat' );
function rewrite_rules_services_cat( $wp_rewrite ) {
$rules = array();
$taxonomies = get_terms( array(
'taxonomy' => 'cpt_services_cat', 'hide_empty' => false
));
foreach ( $taxonomies as $taxonomy ) {
$taxonomy_slug = get_term_parents_list( $taxonomy->term_id, 'cpt_services_cat', array(
'separator' => '/', 'format' => 'slug', 'link' => false, 'inclusive' => true
));
$rules[ '^services/' . $taxonomy_slug . '?$' ] = 'index.php?' . $taxonomy->taxonomy . '=' . $taxonomy->slug;
}
$rules[ '^services/([^/]*)/?$' ] = 'index.php?cpt_services_cat=$matches[1]';
$rules[ '^services/(.+?)/page/?([0-9]{1,})/?$' ] = 'index.php?cpt_services_cat=$matches[1]&paged=$matches[2]';
$rules[ '^services/(.+?)/([^/]*)/?$' ] = 'index.php?cpt_services=$matches[2]';
$wp_rewrite->rules = $rules + $wp_rewrite->rules;
}
//==========================================================
// reset_rewrite_rules()
// Обновление новый правил перезаписи для mod_cpt_services()
//==========================================================
add_action( 'created_cpt_services_cat', 'reset_rewrite_rules' );
add_action( 'delete_cpt_services_cat', 'reset_rewrite_rules' );
add_action( 'edited_cpt_services_cat', 'reset_rewrite_rules' );
add_action( 'created_cpt_services_tag', 'reset_rewrite_rules' );
add_action( 'delete_cpt_services_tag', 'reset_rewrite_rules' );
add_action( 'edited_cpt_services_tag', 'reset_rewrite_rules' );
function reset_rewrite_rules() {
flush_rewrite_rules();
}
// //@@@+======================================================
// // blocksy / breadcrumbs_services()
// // Добавление страницы Услуги в хлебные крошеки
// //==========================================================
// add_filter( 'blocksy:breadcrumbs:items-array', 'breadcrumbs_services' );
// function breadcrumbs_services( $items ) {
// if ( get_post_type() === 'cpt_services') {
// $items = array_merge(
// array_slice( $items, 0, 1 ), [[ 'name' => 'Услуги', 'url' => home_url('/services') ]],
// array_slice( $items, 1 )
// );
// }
// return $items;
// }
// //==========================================================
// // blocksy / breadcrumbs_services_cat()
// // Замена tax в хлебных крошках
// //==========================================================
// add_filter( 'blocksy:breadcrumbs:items-array', 'breadcrumbs_services_cat' );
// function breadcrumbs_services_cat( $items ) {
// if ( count( $items ) < 3 || ! isset( $items[2][ 'cpt_services_cat' ] )) {
// return $items;
// }
// if ( $items[2][ 'cpt_services_cat' ] !== 'sss' ) {
// return $items;
// }
// $items[2][ 'name' ] = __( 'Custom Label', 'blocksy' );
// return $items;
// }
//@@@+======================================================
// permalink_product()
// Правила перезаписи ссылок для Products-Cat и обновление новый правил
//==========================================================
add_filter( 'init', 'permalink_product' );
function permalink_product( $flash = false ) {
$terms = get_terms( array( 'taxonomy' => 'product_cat', 'post_type' => 'product', 'hide_empty' => false )
);
if ( $terms && ! is_wp_error( $terms )) {
$siteurl = esc_url( home_url( '/' ));
foreach ( $terms as $term ) {
$term_slug = $term->slug;
$baseterm = str_replace( $siteurl, '', get_term_link( $term->term_id, 'product_cat' ) );
add_rewrite_rule( $baseterm . '?$', 'index.php?product_cat=' . $term_slug, 'top' );
add_rewrite_rule( $baseterm . 'page/([0-9]{1,})/?$', 'index.php?product_cat=' . $term_slug . '&paged=$matches[1]', 'top' );
add_rewrite_rule( $baseterm . '(?:feed/)?(feed|rdf|rss|rss2|atom)/?$', 'index.php?product_cat=' . $term_slug . '&feed=$matches[1]', 'top' );
}
}
if ( true === $flash ) {
flush_rewrite_rules( false );
}
}
//==========================================================
// permalink_product_cat()
// Замена слага 'product-category' на 'catalog'
//==========================================================
add_filter( 'term_link', 'permalink_product_cat', 10, 3 );
function permalink_product_cat( $url, $term, $taxonomy ) {
if ( 'product_cat' === $taxonomy ) {
return str_replace( 'product-category/', 'shop/', $url );
}
return $url;
}
//==========================================================
// permalink_flush()
// Обновление пермалинков при создании новой категории каталога
//==========================================================
add_action( 'create_term', 'permalink_flush', 10, 2 );
function permalink_flush( $term_id, $taxonomy ) {
if ( 'product_cat' === $taxonomy ) {
permalink_product( true );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment