У меня есть целевая страница, на которой отображаются все сообщения с пользовательским типом сообщения.Я создал раскрывающиеся фильтры, которые используют настраиваемые поля и таксономии.Я хочу скрыть все сообщения, которые не соответствуют выбранным значениям раскрывающегося списка.
Это было закодировано ранее на моем сайте и работает, но я попытался скопировать код для второго типа сообщения, и он не работает, как ожидалось.В раскрывающихся списках заполняются правильные значения таксономии, однако, когда выбраны какие-либо из раскрывающихся списков, они ничего не делают ... без фильтрации, ничего.Они действительно работают с исходным кодом, но не с моим скопированным кодом (обратите внимание, я скопировал все и просто изменил имя типа записи. Я думаю, что проблема заключается в коде JS где-то, но я точно не знаю.
У меня есть настраиваемый тип записи с настраиваемыми таксономиями в Wordpress functions.php:
//Charter Content East Type
$charter_labels = array(
'name' => _x('Charter Aircraft East', 'post type general name'),
'singular_name' => _x('Charter Aircraft East', 'post type singular name'),
'add_new' => _x('Add New', 'news-post'),
'add_new_item' => __('Add New Charter Aircraft East'),
'edit_item' => __('Edit Charter Aircraft East'),
'new_item' => __('New Charter Aircraft East'),
'view_item' => __('View Charter Aircraft East'),
'search_items' => __('Search Charter Aircraft East'),
'not_found' => __('No Charter Aircraft found East'),
'not_found_in_trash' => __('No Charter Aircraft East found in Trash'),
'menu_name' => 'Charter Fleet East'
);
$charter_args = array(
'labels' => $charter_labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'menu_icon' => '/wp-content/themes/avjet/style/img/airplane-admin-icon.png',
'query_var' => true,
'rewrite' => array('slug'=>'private-jet-charter-fleet-east', 'with_front'=>false, 'feeds'=>true, 'pages'=>true),
'capability_type' => 'post',
'has_archive' => true,
'hierarchical' => false,
'supports' => array('title','editor','author','trackbacks','custom-fields','revisions','thumbnail','page-attributes')
);
register_post_type( 'charter-east' , $charter_args );
Затем я регистрирую настраиваемую таксономию:
$c_manufacturer3_labels = array(
'name' => _x( 'Manufacturer / Model', 'taxonomy general name' ),
'singular_name' => _x( 'Manufacturer / Model', 'taxonomy singular name' ),
'search_items' => __( 'Search Manufacturers' ),
'all_items' => __( 'All Manufacturers' ),
'edit_item' => __( 'Edit Manufacturer / Model' ),
'update_item' => __( 'Update Manufacturer / Model' ),
'add_new_item' => __( 'Add New Manufacturer / Model' ),
'new_item_name' => __( 'New Manufacturer / Model' ),
'menu_name' => __( 'Manufacturers' ),
);
$c_manufacturer3_args = array(
'hierarchical' => true,
'labels' => $c_manufacturer3_labels,
'show_ui' => true,
'query_var' => true,
'rewrite' => array('slug' => 'charter-manufacturers3', 'with_front' => true)
);
register_taxonomy('charter-manufacturers3', array('charter-east'), $c_manufacturer3_args);
Это все работает правильно.
Затем я отображаю списки на внешнем интерфейсе:
<div id="pagetext">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php the_content(); ?>
<?php endwhile; endif; ?>
<div class="sorting">
<label>Sort Results 2:</label>
<?php
//Get the search variables, if they exist
$passengers = -1;
$manufacturer = -1;
$model = -1;
$group = -1;
if ($_GET['passengers']) {
$passengers = $_GET['passengers'];
}
if ($_GET['manufacturer']) {
$manufacturer = $_GET['manufacturer'];
}
if ($_GET['model']) {
$model = $_GET['model'];
}
if ($_GET['group']) {
$group = $_GET['group'];
}
//Get the maximum Number of Passengers to create the proper drop-down options
$max = 4;
$charter_args = array(
'post_type' => 'charter-east',
'nopaging' => true,
'orderby' => 'menu_order',
'order' => 'ASC',
);
$charter_query = new WP_Query($charter_args);
if ($charter_query->have_posts()) : while ($charter_query->have_posts()) : $charter_query->the_post();
if (get_field('number_of_passengers') > $max) {
$max = get_field('number_of_passengers');
}
endwhile; endif;
?>
<select id="passengers">
<option value="-1">Number of Passengers</option>
<?php for ($i=4; $i <= $max; $i++) { ?>
<option value="<?php echo $i; ?>" <?php if ($passengers == $i) { echo 'selected="selected"'; } ?>><?php echo $i; ?></option>
<?php } ?>
</select>
<?php wp_reset_query(); ?>
<?php wp_dropdown_categories('show_option_none=Aircraft Manufacturer&taxonomy=charter-manufacturers3&orderby=name&name=manufacturer&id=manufacturer&hierarchical=1&depth=1&hide_empty=1&selected='.$manufacturer); ?>
<div id="modeldrop">
<select id="model" disabled="disabled">
<option value="-1">Aircraft Model</option>
</select>
</div>
<?php wp_dropdown_categories('show_option_none=Aircraft Category&taxonomy=charter-groups&orderby=name&name=group&id=group&hierarchical=1&depth=1&hide_empty=1&selected='.$group); ?>
<?php
//Create a drop-down for each of the Manufacturer's Sub-Categories (Models)
$catargs = array(
'taxonomy' => 'charter-manufacturers3',
'hierarchical' => 1,
'depth' => 1,
'hide_empty' => 1
);
$categories = get_categories($catargs);
foreach ($categories as $cat) {
$dropargs = array(
'show_option_none' => 'Aircraft Model',
'taxonomy' => 'charter-manufacturers3',
'orderby' => 'name',
'child_of' => $cat->term_id,
'hide_if_empty' => 1,
);
if ($cat->term_id == $manufacturer) {
$dropargs['selected'] = $model;
}
echo '<div id="cat-'.$cat->term_id.'" class="hidden">';
wp_dropdown_categories($dropargs);
echo '</div>';
}
?>
</div>
<?php
$_terms = get_terms( array('charter-groups') );
foreach ($_terms as $term) :
$term_slug = $term->slug;
$_posts = new WP_Query( array(
'post_type' => 'charter-east',
'posts_per_page' => 2000, //important for a PHP memory limit warning
'tax_query' => array(
array(
'taxonomy' => 'charter-groups',
'field' => 'slug',
'terms' => $term_slug,
),
),
));
if( $_posts->have_posts() ) :
echo '<section class="groups" style="clear:both;">';
echo '<h2 class="group-name">'. $term->name .'</h3>';
while ( $_posts->have_posts() ) : $_posts->the_post();
?>
<div class="listing charter" manufacturers="<?php foreach((get_the_terms($post->ID, 'charter-manufacturers3')) as $m) { echo $m->term_id.' '; } ?>" passengers="<?php the_field('number_of_passengers'); ?>" groups="<?php foreach((get_the_terms($post->ID, 'charter-groups')) as $g) { echo $g->term_id.' '; } ?>">
<a class="aircraft-thumb" href="<?php the_permalink(); ?>"><?php the_post_thumbnail('aircraft-slideshow-large'); ?></a>
<h2><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
<ul>
<li><?php the_field('bullet_1'); ?></li>
<li><?php the_field('bullet_2'); ?></li>
<li><?php the_field('bullet_3'); ?></li>
<?php if (get_field('bullet_4')) { ?>
<li><?php the_field('bullet_4'); ?></li>
<?php } ?>
<?php if (get_field('bullet_5')) { ?>
<li><?php the_field('bullet_5'); ?></li>
<?php } ?>
</ul>
</div>
<?php
endwhile;
echo '</section>';
endif;
wp_reset_postdata();
endforeach;
?>
Это также работает правильно (обратите внимание, что списки разделены на «группы», что является другим обычаемТаксономия, зарегистрированная так же, как «производитель»).
Наконец, у меня есть JS, который ДОЛЖЕН отфильтровать результаты при выборе, если производитель соответствует правильно. При выборе ничего не происходит (без сообщений об ошибках в консоли).
//Shows/Hides the Aircraft on the Listing Pages
var AircraftSorting =
{
init: function()
{
//Get an array of the drop-downs
var drps = $$('div.sorting select');
for (i=0; i<drps.length; i++) {
Event.observe(drps[i], 'change', AircraftSorting.filter.bindAsEventListener(drps[i]));
}
//Do the initial filter (in case the user submitted a search form)
//Get an array of all the listings to work with
var els = $$('div.listing');
if ($('passengers')) {
var psg = $('passengers');
var psgval = psg.getValue();
if (Number(psgval) > 0) {
for (i = 0; i < els.length; i++) {
var pass = els[i].readAttribute('passengers');
if (Number(pass) < Number(psgval)) {
els[i].hide();
els[i].addClassName('h_passenger');
}
}
}
}
var man = $('manufacturer');
var group = $('group');
var manval = man.getValue();
var groupval = group.getValue();
if (Number(manval) > 0) {
//Show the proper Model element
var newdrp = $('cat-'+manval).clone(true);
$('modeldrop').update(newdrp);
newdrp.removeClassName('hidden');
newdrp.firstDescendant().writeAttribute('id', 'model');
newsel = newdrp.firstDescendant();
Event.observe(newsel, 'change', AircraftSorting.filter.bindAsEventListener(newsel));
for (i = 0; i < els.length; i++) {
var mans = els[i].readAttribute('manufacturers');
var match = mans.search(manval);
if (match == -1) {
els[i].hide();
els[i].addClassName('h_manufacturer');
}
}
var modval = newdrp.getValue();
if (Number(modval) > 0) {
for (i = 0; i < els.length; i++) {
var mans = els[i].readAttribute('manufacturers');
var match = mans.search(modval);
if (match == -1) {
els[i].hide();
els[i].addClassName('h_manufacturer');
}
}
}
}
},
filter: function(event)
{
//Get the selected value of the drop-down
var sortval = this.getValue();
//alert (sortval);
//Get an array of all the listings to work with
var els = $$('div.listing');
//If the manufacturer select element was used, show the proper model element
if (this.id == 'manufacturer') {
if (sortval == -1) {
//Reset the manufacturer sorting
$('modeldrop').update('<select id="model" disabled="disabled"><option value="-1">Aircraft Model</option></select>');
} else {
//Show the proper Model element
var newdrp = $('cat-'+sortval).clone(true);
$('modeldrop').update(newdrp);
newdrp.removeClassName('hidden');
newdrp.firstDescendant().writeAttribute('id', 'model');
newsel = newdrp.firstDescendant();
Event.observe(newsel, 'change', AircraftSorting.filter.bindAsEventListener(newsel));
}
}
//Hide listings that don't match the manufacturer
if (this.id == 'manufacturer' || this.id == 'model') {
if (sortval == -1) {
//Reset the manufacturer sorting
for (i = 0; i < els.length; i++) {
//Remove the class so we know this isn't the reason it's hidden
els[i].removeClassName('h_manufacturer');
if (els[i].hasClassName('h_passenger') || els[i].hasClassName('h_group')) {
//Do nothing because the aircraft is hidden for the passenger count
} else {
els[i].show();
}
}
if (this.id == 'model') {
//We still need to hide based on the manufacturer drop-down
sortval = $('manufacturer').options[$('manufacturer').selectedIndex].value;
for (i = 0; i < els.length; i++) {
var mans = els[i].readAttribute('manufacturers');
var match = mans.search(sortval);
if (match == -1) {
els[i].hide();
els[i].addClassName('h_manufacturer');
} else {
//Remove the class so we know this isn't the reason it's hidden
els[i].removeClassName('h_manufacturer');
if (els[i].hasClassName('h_passenger') || els[i].hasClassName('h_group')) {
//Do nothing because the aircraft is hidden for the passenger count
} else {
els[i].show();
}
}
}
}
} else {
for (i = 0; i < els.length; i++) {
var mans = els[i].readAttribute('manufacturers');
var match = mans.search(sortval);
if (match == -1) {
els[i].hide();
els[i].addClassName('h_manufacturer');
} else {
//Remove the class so we know this isn't the reason it's hidden
els[i].removeClassName('h_manufacturer');
if (els[i].hasClassName('h_passenger') || els[i].hasClassName('h_group')) {
//Do nothing because the aircraft is hidden for the passenger count
} else {
els[i].show();
}
}
}
}
}
//Hide listings that don't match the manufacturer
if (this.id == 'group' ) {
if (sortval == -1) {
//Reset the manufacturer sorting
for (i = 0; i < els.length; i++) {
//Remove the class so we know this isn't the reason it's hidden
els[i].removeClassName('h_group');
if (els[i].hasClassName('h_passenger') || els[i].hasClassName('h_manufacturer')) {
//Do nothing because the aircraft is hidden for the passenger count
} else {
els[i].show();
}
}
if (this.id == 'model') {
//We still need to hide based on the manufacturer drop-down
sortval = $('manufacturer').options[$('manufacturer').selectedIndex].value;
for (i = 0; i < els.length; i++) {
var mans = els[i].readAttribute('manufacturers');
var match = mans.search(sortval);
if (match == -1) {
els[i].hide();
els[i].addClassName('h_manufacturer');
} else {
//Remove the class so we know this isn't the reason it's hidden
els[i].removeClassName('h_manufacturer');
if (els[i].hasClassName('h_passenger') || els[i].hasClassName('h_group')) {
//Do nothing because the aircraft is hidden for the passenger count
} else {
els[i].show();
}
}
}
}
} else {
for (i = 0; i < els.length; i++) {
var mans = els[i].readAttribute('groups');
var match = mans.search(sortval);
if (match == -1) {
els[i].hide();
els[i].addClassName('h_group');
} else {
//Remove the class so we know this isn't the reason it's hidden
els[i].removeClassName('h_group');
if (els[i].hasClassName('h_passenger') || els[i].hasClassName('h_manufacturer') ) {
//Do nothing because the aircraft is hidden for the passenger count
}
else {
els[i].show();
}
}
}
}
}
//Hide listings that don't match the passenger count
if (this.id == 'passengers') {
for (i = 0; i < els.length; i++) {
var pass = els[i].readAttribute('passengers');
if (Number(pass) >= Number(sortval)) {
//Remove the class so we know this isn;t the reason it's hidden
els[i].removeClassName('h_passenger');
if (els[i].hasClassName('h_manufacturer')) {
//Do nothing because the aircraft is hidden for the manufacturer
} else {
els[i].show();
}
} else {
els[i].hide();
els[i].addClassName('h_passenger');
}
}
}
}
}
В JS есть какой-то другой код для некоторых других раскрывающихся списков, которые являются либо пользовательскими таксономиями, либо пользовательскими полями, добавляемыми к типу публикации через Advanced Custom.Поля Pro.Все части работают, кроме выпадающих списков, которые скрывают не выбранные списки.