Created
June 1, 2021 14:00
-
-
Save Prroffessorr/b5117439fa4c2316cfb4b3997ada30e5 to your computer and use it in GitHub Desktop.
Wordpress. Как создать свой фильтр для постов (Выбор по нескольким параметрам) Carbon fields + WP_query
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//Добавление своего типа поста с полной настройкой. | |
add_action('init', 'activities_init'); | |
function activities_init() { | |
$labels = array( | |
'name' => __('Мероприятия'), | |
'singular_name' => __('Мероприятие'), | |
'add_new' => __('Добавить новое'), | |
'all_items' => __('Все Мероприятия'), | |
'add_new_item' => __('Добавить новое'), | |
'edit_item' => __('Редактировать'), | |
'new_item' => __('Новый'), | |
'view_item' => __('Просмотреть'), | |
'search_items' => __('Поиск'), | |
'not_found' => __('Ничего не найдено'), | |
'not_found_in_trash' => __('Корзина пустая'), | |
'parent_item_colon' => __(''), | |
'menu_name' => __('Мероприятия'), | |
'name_admin_bar' => 'Мероприятия', | |
); | |
$args = array( | |
'labels' => $labels, | |
'public' => true, | |
'publicly_queryable' => true, | |
'show_ui' => true, | |
'show_in_admin_bar' => true, | |
'show_in_menu' => true, | |
'query_var' => true, | |
'rewrite' => true, | |
'capability_type' => 'post', | |
'has_archive' => true, | |
'hierarchical' => false, | |
'menu_position' => 4, | |
'menu_icon' => 'dashicons-plus', | |
'hierarchical' => false, | |
'has_archive' => false, | |
'can_export' => true, | |
'query_var' => true, | |
'supports' => array('title', 'editor', 'thumbnail'), | |
'taxonomies' => ['activity-category'], | |
); | |
register_post_type('activity', $args); | |
register_taxonomy('activity-category', array('activity'), array( | |
"label" => __("Категории"), | |
"singular_label" => __("Категория"), | |
'name' => 'activity', | |
'hierarchical' => true, | |
'show_ui' => true, | |
'show_in_nav_menus' => false, | |
'args' => array('orderby' => 'term_order'), | |
'query_var' => true, | |
'show_admin_column' => true, | |
'labels' => array( | |
'name' => _x('Категории', 'taxonomy general name'), | |
'singular_name' => _x('Категории', 'taxonomy singular name'), | |
'search_items' => __('Поиск категорий'), | |
'all_items' => __('Все категории'), | |
//'parent_item' => __('Parent Location'), | |
//'parent_item_colon' => __('Parent Location:'), | |
'edit_item' => __('Настройка категории'), | |
'update_item' => __('Обновить категорию'), | |
'add_new_item' => __('Добавить новую категорию'), | |
'new_item_name' => __('Имя новой категории'), | |
'menu_name' => __('Категории'), | |
), | |
// Control the slugs used for this taxonomy | |
'rewrite' => array( | |
'slug' => 'activity', // This controls the base slug that will display before each term | |
'with_front' => false, // Don't display the category base before "/locations/" | |
'hierarchical' => true // This will allow URL's like "/locations/boston/cambridge/" | |
), | |
)); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//Получение параметров созданого поста. Для обычных постов используйте $terms = get_queried_object(); | |
$terms = get_terms("activity-category", array( | |
'hide_empty' => 0, | |
)); | |
?> | |
<!--"Кнопки с информацией о категориях постов" --> | |
<?php $iterator = 2; ?> | |
<a href="#tab-1" id="item-all" class="tabs-triggers__item" onclick="$('#category-1').trigger('click');"><?php echo carbon_get_the_post_meta('plug_activtiy_category'); ?></a> | |
<input type="radio" name="get_cat_filter" id="category-1" value="All" hidden="true" /> | |
<?php | |
if (count($terms) > 0) : | |
foreach ($terms as $term) : | |
$locations[] = $term->name; ?> | |
<input type="radio" name="get_cat_filter" id="category-<?php echo $iterator; ?>" value="<?php echo $term->slug; ?>" hidden="true" /> | |
<a href="#tab-<?php echo $iterator; ?>" id="tabs-triggers" class="tabs-triggers__item" onclick="$('#category-<?php echo $iterator; ?> ').trigger('click');"><?php echo $term->name; ?></a> | |
<?php | |
$iterator++; | |
endforeach; | |
endif; | |
?> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//Не обязательный фрагмет. Использовался только в проекте, где был ввод множества значений в поля Carbon fields. | |
//Мы их получаем и разбиваем на уникальные массивы, значения которых будут выведены в соответсвующих фильтрах | |
$args = array( | |
'post_type' => 'activity', | |
); | |
$all_ages = ""; | |
$query = new WP_Query($args); | |
while ($query->have_posts() ): | |
$query->the_post(); | |
if(carbon_get_the_post_meta('activity_city')){ | |
$cities[] = carbon_get_the_post_meta('activity_city'); | |
} | |
if(carbon_get_the_post_meta('activity_metro')){ | |
$accept_metro.= carbon_get_the_post_meta('activity_metro').", "; | |
$metro=explode(", ", $accept_metro); | |
} | |
if(carbon_get_the_post_meta('activity_all_ages')){ | |
$all_ages=true; | |
} | |
$accept_ages.=carbon_get_the_post_meta('activity_age').","; | |
$ages=explode(",", $accept_ages); | |
endwhile; | |
wp_reset_postdata(); | |
$get_unique_city=array_unique($cities); | |
$get_unique_metro=array_diff(array_unique($metro), array('', NULL, false)); | |
$get_unique_ages=array_diff(array_unique($ages), array('', NULL, false)); | |
$iterator=1; | |
sort($get_unique_city); | |
?> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div class="select__body"> | |
<?php //Фильтр "Городов" ?> | |
<input type="radio" name="get_city" id="city-0" value="All" hidden="true" /> | |
<div class="select__item all_element" id="get_city" onclick="$('#city-0').trigger('click');"><?php echo carbon_get_theme_option("resset_all_city"); ?></div> | |
<?php foreach ($get_unique_city as $city) : ?> | |
<input type="radio" name="get_city" id="city-<?php echo $iterator; ?>" value="<?php echo $city; ?>" hidden="true" /> | |
<div class="select__item" id="get_city" onclick="$('#city-<?php echo $iterator; ?> ').trigger('click');"><?php echo $city; ?></div> | |
<?php | |
$iterator++; | |
endforeach; ?> | |
</div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php //Фильтр Метро ?> | |
<form class="select__body-check"> | |
<?php $iterator = 1; | |
sort($get_unique_metro); | |
foreach ($get_unique_metro as $metro) : ?> | |
<input type="checkbox" name="get_metro" class="checkbox-input-metro" value="<?php echo $metro; ?>" id="metro-<?php echo $iterator; ?>" /> | |
<label class="select__item-check" for="metro-<?php echo $iterator; ?>"><?php echo $metro; ?></label> | |
<?php | |
$iterator++; | |
endforeach; ?> | |
</form> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php //Фильтр Города ?> | |
<form class="select__body-check"> | |
<?php | |
$iterator = 0; | |
natcasesort($get_unique_ages); | |
foreach ($get_unique_ages as $age) : ?> | |
<input type="checkbox" name="get_age" class="checkbox-input" value="<?php echo $age; ?>" id="check-<?php echo $iterator; ?>" /> | |
<label class="select__item-check" for="check-<?php echo $iterator; ?>"> | |
<?php echo $age; ?></label> | |
<?php | |
$iterator++; | |
endforeach; ?> | |
</form> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php //Вывод всех кастомных постов без использования фильрации ?> | |
<div class="slider"> | |
<?php | |
$params = array( | |
'post_type' => 'activity', | |
'posts_per_page' => 10, | |
); | |
$iterator = 1; | |
$query = new WP_Query($params); | |
if (!empty($query)) { | |
$term = get_term_by('slug', get_query_var('term'), get_query_var('taxonomy')); | |
while ($query->have_posts()) : | |
$query->the_post(); ?> | |
<a href="<?php echo get_permalink(); ?>" class="slider__item"> | |
<span id='time-<?php echo $iterator; ?>'> | |
<?php | |
$get_date_format = carbon_get_the_post_meta('crb_event_start_date') . ' ' . carbon_get_the_post_meta('crb_event_start_time'); | |
echo date("Y.n.d H:i:s", strtotime($get_date_format)); ?></span> | |
<div class="slider__info info-slide"> | |
<div class="info-slide__time"> | |
<?php $activity_date = new DateTime($get_date_format); ?> | |
<div class="info-slide__num-day"><?php echo $activity_date->format('d'); ?></div> | |
<div class="info-slide__month"><?php echo _e($activity_date->format('F')); ?></div> | |
<div class="info-slide__day"><?php echo _e($activity_date->format('l')); ?></div> | |
</div> | |
<div class="info-slide__twinkle "> | |
<p><?php echo carbon_get_theme_option('slider_nearest_activtiy'); ?></p> | |
</div> | |
<div class="info-slide__additionally"> | |
<div class="info-slide__competition-for"><?php the_title(); ?></div> | |
<div class="info-slide__num-time"><?php echo $activity_date->format('H:i'); ?></div> | |
<div class="info-slide__place"> <?php echo carbon_get_the_post_meta('activity_city_text'); ?> : <?php echo carbon_get_the_post_meta('activity_city'); | |
if (carbon_get_the_post_meta('activity_metro')) { ?> , <?php } | |
echo carbon_get_the_post_meta('activity_metro'); ?> | |
<?php echo carbon_get_the_post_meta('activity_complex'); ?></div> | |
</div> | |
</div> | |
<img src="<?php echo get_the_post_thumbnail_url(get_the_ID()); ?>" alt=""> | |
</a> | |
<?php | |
$iterator++; | |
endwhile; | |
wp_reset_postdata(); | |
}; ?> | |
</div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
jQuery(document).ready(function($){ | |
categoty=null; | |
city=null; | |
metro=null; | |
ages=null; | |
all_ages=null; | |
// Стандартный фильтр по категориям | |
$('.tabs-triggers__item').click(function(){ | |
//document.getElementsByClassName("slick-list")[0].innerHTML=" "; | |
var get_categoty=document.getElementsByName("get_cat_filter") | |
for (var i=0; i<get_categoty.length;i++){ | |
if(document.getElementsByName("get_cat_filter")[i].checked==true){ | |
categoty=document.getElementsByName("get_cat_filter")[i].defaultValue; | |
console.log(categoty); | |
} | |
} | |
var calc= { | |
'action': 'activity_filter', | |
'dataType' : "json", | |
'categoty':categoty, | |
'city':city, | |
'metro':metro, | |
'ages':ages, | |
'all_ages':all_ages | |
}; | |
jQuery.post( ajaxurl, calc, function( response ) { | |
console.log(response); | |
document.getElementsByClassName("slider")[0].innerHTML = response; | |
document.getElementById("resset-all-text").style.display = "block"; | |
}); | |
}); | |
//Фильтр по городам | |
$('.select__item').click(function(){ | |
var get_city=document.getElementsByName("get_city"); | |
for (var i=0; i<get_city.length;i++){ | |
if(document.getElementsByName("get_city")[i].checked==true){ | |
city=document.getElementsByName("get_city")[i].defaultValue; | |
if(city!="All"){ | |
document.getElementById("get_city").style.display ="block"; | |
} | |
else{ | |
document.getElementById("get_city").style.display ="none"; | |
} | |
console.log(city); | |
} | |
} | |
var calc= { | |
'action': 'activity_filter', | |
'dataType' : "json", | |
'categoty':categoty, | |
'city':city, | |
"metro":metro, | |
'ages':ages, | |
'all_ages':all_ages | |
}; | |
jQuery.post( ajaxurl, calc, function( response ) { | |
console.log(response); | |
document.getElementsByClassName("slider")[0].innerHTML = response; | |
document.getElementById("resset-all-text").style.display = "block"; | |
}); | |
}); | |
//Фильтр по районам метро | |
//$('.select__item-metro').click(function(){ | |
$('.checkbox-input-metro').click(function(){ | |
metro=""; | |
var get_metro=document.getElementsByName("get_metro"); | |
for (var i=0; i<get_metro.length;i++){ | |
if(document.getElementsByName("get_metro")[i].checked==true){ | |
metro+=document.getElementsByName("get_metro")[i].defaultValue+", "; | |
console.log(metro); | |
} | |
} | |
var calc= { | |
'action': 'activity_filter', | |
'dataType' : "json", | |
'categoty':categoty, | |
'city':city, | |
'metro':metro, | |
'ages':ages, | |
'all_ages':all_ages | |
}; | |
jQuery.post( ajaxurl, calc, function( response ) { | |
console.log(response); | |
document.getElementsByClassName("slider")[0].innerHTML = response; | |
document.getElementById("resset-all-text").style.display = "block"; | |
}); | |
}); | |
//Фильтр по возрастам | |
$('.checkbox-input').click(function(){ | |
// console.log(document.getElementsByName("get_age")); | |
var get_ages=document.getElementsByName("get_age") | |
ages=""; | |
for (var i=0; i<get_ages.length;i++){ | |
if(document.getElementsByName("get_age")[i].checked==true){ | |
ages+=document.getElementsByName("get_age")[i].defaultValue+","; | |
} | |
} | |
console.log(ages); | |
var calc= { | |
'action': 'activity_filter', | |
'dataType' : "json", | |
'categoty':categoty, | |
'city':city, | |
'metro':metro, | |
'ages':ages, | |
'all_ages':all_ages | |
}; | |
jQuery.post( ajaxurl, calc, function( response ) { | |
console.log(response); | |
document.getElementsByClassName("slider")[0].innerHTML = response; | |
document.getElementById("resset-all-text").style.display = "block"; | |
}); | |
}); | |
$('.checkbox-input-all').click(function(){ | |
var get_all_ages=document.getElementsByName("all_ages") | |
all_ages=""; | |
for (var i=0; i<get_all_ages.length;i++){ | |
if(document.getElementsByName("all_ages")[i].checked==true){ | |
all_ages=document.getElementsByName("all_ages")[i].defaultValue; | |
} | |
} | |
//alert(all_ages); | |
var calc= { | |
'action': 'activity_filter', | |
'dataType' : "json", | |
'categoty':categoty, | |
'city':city, | |
'metro':metro, | |
'ages':ages, | |
'all_ages':all_ages | |
}; | |
jQuery.post( ajaxurl, calc, function( response ) { | |
document.getElementById("resset-all-text").style.display = "block"; | |
console.log(response); | |
document.getElementsByClassName("slider")[0].innerHTML = response; | |
}); | |
}); | |
//Resset | |
$('.reset_current').click(function(){ | |
categoty=null; | |
city=null; | |
metro=null; | |
ages=null; | |
all_ages=null; | |
var calc= { | |
'action': 'activity_filter', | |
'dataType' : "json", | |
'categoty':categoty, | |
'city':city, | |
'metro':metro, | |
'ages':ages, | |
'all_ages':all_ages | |
}; | |
jQuery.post( ajaxurl, calc, function( response ) { | |
document.getElementsByClassName("slider")[0].innerHTML = response; | |
var get_categoty=document.getElementsByClassName("tabs-triggers__item") | |
for (var i=0; i<get_categoty.length;i++){ | |
get_categoty[i].className="tabs-triggers__item" | |
} | |
document.getElementById("item-all").className += " tabs-triggers__item--active"; | |
document.getElementById("resset-all-text").style.display = "none"; | |
}); | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//Фильтрация кастомных типов постов | |
add_action('wp_ajax_activity_filter', 'activity_filter_function'); | |
add_action('wp_ajax_nopriv_activity_filter', 'activity_filter_function'); | |
function activity_filter_function() { | |
$activity_cat = $_POST['categoty']; | |
$activity_city = $_POST['city']; | |
$activity_metro = $_POST['metro']; | |
$activity_ages = $_POST['ages']; | |
$activity_get_all_ages = $_POST['all_ages']; | |
//Получаем наши возраста _activity_age | |
$array_ages = array_diff(explode(',', $activity_ages ), array('', NULL, false)); | |
//Получаем список _activity_metro | |
$array_metro = array_diff(explode(', ', $activity_metro ), array('', NULL, false)); | |
//Проверка на наличие выбранной категории | |
if ($_POST['categoty'] && $_POST['categoty']!="All") { | |
$param_activity = array( | |
'taxonomy' => 'activity-category', | |
'field' => 'slug', | |
'terms' => $activity_cat | |
); | |
} | |
else{ | |
$param_activity= array( | |
'taxonomy' => 'activity-category', | |
'operator' => "EXISTS" | |
); | |
} | |
//Получаем данные для городов | |
if(!empty($activity_city) && $activity_city!="All"){ | |
$param_city=array( | |
'state_clause' => array( | |
'key' => '_activity_city', | |
'value' => $activity_city, | |
), | |
); | |
} | |
else{ | |
$param_city=array('key'=>'_activity_city'); | |
} | |
//Для метро | |
if(!empty($activity_metro)){ | |
foreach($array_metro as $arr){ | |
$param_metro[]=array( | |
'relation' => 'OR',[ | |
'key' => '_activity_metro', | |
'compare' => 'LIKE', | |
'value' => $arr, | |
] | |
); | |
} | |
} | |
else{ | |
$param_metro=array('key'=>'_activity_metro'); | |
} | |
//Получаем данные о возрастах | |
if(!empty($array_ages)){ | |
foreach($array_ages as $arr){ | |
$param_age[]=array( | |
'relation' => 'OR',[ | |
'key' => '_activity_age', | |
'compare' => 'LIKE', | |
'value' => $arr, | |
] | |
); | |
} | |
} | |
else{ | |
$param_age=array('key'=>'_activity_age'); | |
} | |
if(!empty($activity_get_all_ages)){ | |
if($_POST['categoty'] && $_POST['categoty']!="All" ){ | |
$param_activity = array( | |
'taxonomy' => 'activity-category', | |
'field' => 'slug', | |
'terms' => $activity_cat | |
); | |
} | |
else{ | |
$param_activity=null; | |
} | |
$param_age=array( | |
'key'=>'_activity_all_ages', | |
'value' => 'yes', | |
); | |
} | |
//Формируем запрос в БД исходя из полученных данных | |
$params = array( | |
'post_type' => 'activity', | |
'posts_per_page' => 10, | |
'tax_query' => [ | |
'relation' => 'AND', | |
[ | |
$param_activity | |
] | |
], | |
'meta_query' => array( | |
'relation' => 'AND', | |
$param_city, | |
$param_metro, | |
$param_age, | |
), | |
); | |
global $iterator; | |
global $wpdb; | |
$iterator = 1; | |
$query = new WP_Query($params); ?> | |
<div class="slick-track"> | |
<?php while ($query->have_posts()): | |
$query->the_post(); | |
get_template_part('activity'); | |
endwhile; | |
?> | |
</div> | |
<?php | |
wp_reset_postdata(); | |
die(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//Шаблон для вывода постов после фильрации | |
global $iterator;?> | |
<div class="slick-slide" data-slick-index="<?php echo $iterator; ?>" aria-hidden="true" tabindex="-1" role="tabpanel" id="slick-slide0<?php echo $iterator; ?>" aria-describedby="slick-slide-control0<?php echo $iterator; ?>"> | |
<div> | |
<a href="<?php echo get_permalink(); ?>" class="slider__item"> | |
<span id='time-<?php echo $iterator; ?>'> | |
<?php | |
$get_date_format=carbon_get_the_post_meta('crb_event_start_date').' '.carbon_get_the_post_meta('crb_event_start_time'); | |
echo date("Y.n.d H:i:s", strtotime($get_date_format)); ?></span> | |
<div class="slider__info info-slide"> | |
<div class="info-slide__time"> | |
<?php $activity_date = new DateTime($get_date_format);?> | |
<div class="info-slide__num-day"><?php echo $activity_date->format('d');?></div> | |
<div class="info-slide__month"><?php echo _e($activity_date->format('F'));?></div> | |
<div class="info-slide__day"><?php echo _e($activity_date->format('l')); ?></div> | |
</div> | |
<div class="info-slide__twinkle "> | |
<p><?php echo carbon_get_theme_option('slider_nearest_activtiy'); ?></p> | |
</div> | |
<div class="info-slide__additionally"> | |
<div class="info-slide__competition-for"><?php the_title(); ?></div> | |
<div class="info-slide__num-time"><?php echo $activity_date->format('H:i');?></div> | |
<div class="info-slide__place"> <?php echo carbon_get_the_post_meta('activity_city_text');?> : <?php echo carbon_get_the_post_meta('activity_city'); | |
if(carbon_get_the_post_meta('activity_metro')) { ?> , <?php } | |
echo carbon_get_the_post_meta('activity_metro'); ?> | |
<?php echo carbon_get_the_post_meta('activity_complex'); ?></div> | |
</div> | |
</div> | |
<img src="<?php echo get_the_post_thumbnail_url(get_the_ID()); ?>" alt=""> | |
</a> | |
</div> | |
</div> | |
<?php $iterator++; ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment