根据第一个下拉列表(CPT)筛选第二个下拉列表(Tax)

时间:2014-08-24 作者:Guit4eva

我已经在谷歌上搜索并尝试了一个多星期,但没有成功。我有一些自定义的帖子类型(书籍、电影、音乐等)和自定义的分类法(位置)。

在我的frontpage上,有两个下拉列表可以过滤搜索,如下所示:

Look for: <custom post type> in <taxonomy>
我想做的是根据第一个下拉列表(cpt)过滤第二个下拉列表(位置)。因此,如果我选择“book”,并且town X和town Y中只有book,那么在第二个下拉列表中只显示town X和Y作为选项。如果有人能帮我把它做好,你会让我整整一年都开心!下面是我的两个下拉列表代码(正在运行,只是没有过滤):

<form action="<?php bloginfo(\'url\'); ?>" method="get">

<?php 

$args = array(
\'public\'   => true,
\'_builtin\' => false
);

$output = \'objects\'; // names or objects, note names is the default
$operator = \'and\'; // \'and\' or \'or\'

$post_types = get_post_types($args, $output, $operator);

echo \'<select class="selectboxSingle" name="post_type">\';

foreach ( $post_types  as $post_type ) {

$exclude = array(\'custom_type\');

if(TRUE === in_array($post_type->name,$exclude))
continue;

   echo \'<option value="\'.$post_type->slug.\'">\' . ucfirst($post_type->name) . \'</option>\';
}

echo "</select>";
?>

<div class="inx">in</div>

<?php 

// Set your custom taxonomy
$taxonomy = "location";

// Get all terms of the chosen taxonomy
$terms = get_terms($taxonomy, array(\'orderby\' => \'name\'));

// our content variable
$list_of_terms = \'<select id="location" class="selectboxSingle" name="location">\';

foreach($terms as $term){

    $select = ($current_selected = $term->slug) ? "selected" : "";

    if ($term->parent == 0 ) {

        // get children of current parent.
        $tchildren = get_term_children($term->term_id, $taxonomy);

    $children = array();
    foreach ($tchildren as $child) {
        $cterm = get_term_by( \'id\', $child, $taxonomy );
        $children[$cterm->name] = $cterm;
    }
    ksort($children);

    // OPTGROUP FOR PARENTS
    if (count($children) > 0 ) {
             $list_of_terms .= \'<optgroup label="\'. $term->name .\'">\';
             if ($term->count > 0)
             $list_of_terms .= \'<option value="\'.$term->slug.\'" \'.$select.\'>All \'. $term->name .\' </option>\';
        } else
        $list_of_terms .= \'<option value="\'.$term->slug.\'" \'.$select.\'>\'. $term->name .\' </option>\';
    //$i++;

    // now the CHILDREN.
    foreach($children as $child) {
         $select = ($current_selected == $cterm->slug) ? "selected" : "";
         $list_of_terms .= \'<option value="\'.$child->slug.\'" \'.$select.\'>\'. $child->name.\' </option>\';

    } //end foreach

    if (count($children) > 0 ) {
        $list_of_terms .= "</optgroup>";
    }
}
}

$list_of_terms .= \'</select>\';

echo $list_of_terms; 
?>

</div>
<div class="submit-button-blanket"><button class="submit-button" type="submit">Search</button></div>
</form>
</div>

2 个回复
最合适的回答,由SO网友:bonger 整理而成

如果您想要一个如何使用ajax进行下拉筛选的示例,那么如果您将分类法下拉列表分解到“functions.php”中:

function my_dropdown_categories( $taxonomy, $current_selected = \'\', $include = null ) {
    // Get all terms of the chosen taxonomy
    $terms = get_terms($taxonomy, array(\'orderby\' => \'name\'));

    // our content variable
    $list_of_terms = \'<select id="location" class="selectboxSingle" name="location">\';

    if ( ! is_wp_error( $terms ) ) foreach($terms as $term){

        // If include array set, exclude unless in array.
        if ( is_array( $include ) && ! in_array( $term->slug, $include ) ) continue;

        $select = ($current_selected == $term->slug) ? "selected" : ""; // Note: ==

        if ($term->parent == 0 ) {

            // get children of current parent.
            $tchildren = get_term_children($term->term_id, $taxonomy);

            $children = array();
            foreach ($tchildren as $child) {
                $cterm = get_term_by( \'id\', $child, $taxonomy );
                // If include array set, exclude unless in array.
                if ( is_array( $include ) && ! in_array( $cterm->slug, $include ) ) continue;
                $children[$cterm->name] = $cterm;
            }
            ksort($children);

            // OPTGROUP FOR PARENTS
            if (count($children) > 0 ) {
                 $list_of_terms .= \'<optgroup label="\'. $term->name .\'">\';
                 if ($term->count > 0)
                     $list_of_terms .= \'<option value="\'.$term->slug.\'" \'.$select.\'>All \'. $term->name .\' </option>\';
            } else
                $list_of_terms .= \'<option value="\'.$term->slug.\'" \'.$select.\'>\'. $term->name .\' </option>\';
            //$i++;

            // now the CHILDREN.
            foreach($children as $child) {
                 $select = ($current_selected == $child->slug) ? "selected" : ""; // Note: child, not cterm
                 $list_of_terms .= \'<option value="\'.$child->slug.\'" \'.$select.\'>\'. $child->name.\' </option>\';

            } //end foreach

            if (count($children) > 0 ) {
                $list_of_terms .= "</optgroup>";
            }
        }
    }

    $list_of_terms .= \'</select>\';

    return $list_of_terms;
}
在“functions.php”中,您还加入了ajax处理:

add_action( \'wp_ajax_wpse158929_get_terms_for_cpt\', \'wpse158929_get_terms_for_cpt\' );
add_action( \'wp_ajax_nopriv_wpse158929_get_terms_for_cpt\', \'wpse158929_get_terms_for_cpt\' );

function wpse158929_get_terms_for_cpt() {
    $ret = array( \'html\' => \'\', \'error\' => false );

    if ( ! check_ajax_referer( \'wpse158929_get_terms_for_cpt_submit_\', \'nonce\', false /*die*/ ) ) {
        $ret[\'error\'] = __( \'Permission error\', \'wpfm\' );
    } else {
        $post_type = isset( $_REQUEST[\'post_type\'] ) ? $_REQUEST[\'post_type\'] : \'\';
        $taxonomy = isset( $_REQUEST[\'taxonomy\'] ) ? $_REQUEST[\'taxonomy\'] : \'\';
        $current_selected = isset( $_REQUEST[\'current_selected\'] ) ? $_REQUEST[\'current_selected\'] : \'\';

        if ( ! $post_type || ! $taxonomy ) {
            $ret[\'error\'] = __( \'Params error\', \'wpfm\' );
        } else {
            global $wpdb;
            $sql = $wpdb->prepare( \'SELECT t.slug FROM \' . $wpdb->terms . \' t\'
                . \' JOIN \' . $wpdb->term_taxonomy . \' AS tt ON tt.term_id = t.term_id\'
                . \' JOIN \' . $wpdb->term_relationships . \' AS tr ON tr.term_taxonomy_id = tt.term_taxonomy_id\'
                . \' JOIN \' . $wpdb->posts . \' AS p ON p.ID = tr.object_id\'
                . \' WHERE tt.taxonomy = %s AND p.post_type = %s AND p.post_status = %s\'
                . \' GROUP BY t.slug\'
                , $taxonomy, $post_type, \'publish\' );
            $include = $wpdb->get_col($sql);
            $ret[\'html\'] = preg_replace( \'/<\\/?select[^>]*>/\', \'\', my_dropdown_categories( $taxonomy, $current_selected, $include ) );
        }
    }

    wp_send_json( $ret );
}
然后将jquery附加到主代码中:

<form action="<?php bloginfo(\'url\'); ?>" method="get">

<?php 

$args = array(
\'public\'   => true,
\'_builtin\' => false
);

$output = \'objects\'; // names or objects, note names is the default
$operator = \'and\'; // \'and\' or \'or\'

$post_types = get_post_types($args, $output, $operator);

echo \'<select class="selectboxSingle" name="post_type">\';

foreach ( $post_types  as $post_type ) {

$exclude = array(\'custom_type\');

if(TRUE === in_array($post_type->name,$exclude))
continue;

   // Note: I think you need to use query_var here, rather than slug.
   echo \'<option value="\'.$post_type->query_var.\'">\' . ucfirst($post_type->name) . \'</option>\';
}

echo "</select>";
?>

<div class="inx">in</div>

<?php 

// Set your custom taxonomy
$taxonomy = "location";

// Factored out taxonomy dropdown into function my_dropdown_categories() in "functions.php".
echo my_dropdown_categories( $taxonomy );
?>

</div>
<div class="submit-button-blanket"><button class="submit-button" type="submit">Search</button></div>
</form>
</div>
<script type="text/javascript">
jQuery(document).ready(function() {
    (function ($) {
        $(\'select[name="post_type"]\').change(function (event) {
            $.post( <?php echo json_encode( admin_url( \'admin-ajax.php\' ) ); ?>, {
                    action: \'wpse158929_get_terms_for_cpt\',
                    post_type: $(this).val(),
                    taxonomy: <?php echo json_encode( $taxonomy ); ?>,
                    current_selected: $(\'select[name="location"]\').val(),
                    nonce: <?php echo json_encode( wp_create_nonce( \'wpse158929_get_terms_for_cpt_submit_\' ) ); ?>
                }, function( response ) {
                    if ( response && !response.error ) {
                        $(\'select[name="location"]\').html(response.html);
                    }
                }, \'json\'
            );
        });
        // Remove if you don\'t want to call change immediately.
        $(\'select[name="post_type"]\').change();
    })(jQuery);
});
</script>
你会有办法得到你想要的。

SO网友:Hassan Alvi

在第一个下拉列表中使用jQuery操作。。这是您提到的url中的代码。。您可以使用php函数填充数组。。。

function dynamic1(parent,child)
{
    var parent_array = new Array();
    // This is the default value
    parent_array[\'\'] = [\'Please select a manufacturer\'];
    // All other elements
    // parent_array[\'PARENT NAME\'] = [\'CHILD 1\',\'CHILD 2\',\'CHILD 3\',\'ETC\'];
    parent_array[\'Audi\'] = [\'A3\',\'A4\',\'A5\',\'A6\',\'A8\',\'Q5\',\'Q7\',\'S3\',\'S4\',\'S5\',\'S6\',\'S8\',\'RS6\'];
    parent_array[\'Dacia\'] = [\'Sandero\',\'Logan\'];
    parent_array[\'FIAT\'] = [\'Bravo\',\'Punto\',\'Grande Punto\'];
    parent_array[\'Peugeot\'] = [\'207\',\'308\',\'407\',\'607\'];
    parent_array[\'SEAT\'] = [\'Ibiza\',\'New Ibiza\',\'Leon\'];
    parent_array[\'Skoda\'] = [\'Fabia\',\'Octavia Tour\',\'Octavia 2\',\'Superb\'];

    // Get the child
    var thechild = document.getElementById(child);

    // Remove all other options from the select element
    thechild.options.length = 0;

    // What value are we looking for ?
    var parent_value = parent.options[parent.selectedIndex].value;

    // No value found, use the default value
    if (!parent_array[parent_value]) parent_value = \'\';

    // Set the correct length
    thechild.options.length = parent_array[parent_value].length;

    // Add the options
    for(var i=0;i<parent_array[parent_value].length;i++)
    {
        thechild.options[i].text = parent_array[parent_value][i];
        thechild.options[i].value = parent_array[parent_value][i];
    }
}

结束

相关推荐

GET Taxonomy ID

我有一行,其中“5”是分类ID。<?php echo function xyz (5,\'product_cat\'); ?>如何更改此项以使其始终自动识别当前页面的分类ID?尝试此操作但未成功:<?php echo function xyz (get_term_by(\'id\',\'\',\'product_cat);,\'product_cat\'); ?>我该怎么做?谢谢