Show WordPress Custom Taxonomy Items Based On a Selected Item From Another Custom Taxonomy

Why not make the towns child terms of each state? The taxonomy could be location:

See MikeSchinkel’s detailed q and a regarding hierarchal taxonomies.

enter image description here

A more elegant solution than refreshing the page upon state selected would be to load the “thetown” child terms using ajax and the get_term_children function or the custom $wpdb query outlined below.

Pass the state selected using jQuery to your back end PHP function that loops through an array of child terms to build out your second drop down.

Here is a quick example using a custom $wpdb query:

PHP backend function:

add_action( 'wp_ajax_nopriv_get_child', 'ajax_get_children' );

function ajax_get_children() {
        global $wpdb;
        $parent = $_POST['parent'];
        $child_string = "";
        $results = $wpdb->get_results ( "SELECT t.term_id, t.name FROM $wpdb->term_taxonomy tt, $wpdb->terms t, $wpdb->term_taxonomy tt2 WHERE tt.parent = $parent AND tt.taxonomy = 'category' AND t.term_id = tt.term_id AND tt2.parent = tt.term_id GROUP BY t.term_id, t.name HAVING COUNT(*) > 0 ORDER BY t.term_order ASC" );
        foreach ( $results as $row ) {
            $child_string = $child_string . "<option value="$row->term_id">$row->name</option>";
        }
        echo $child_string;

        die(1);

    }

jQuery:

jQuery(document).ready(function() {

    jQuery("#div-id-of-dropdown").select(function(){

        jQuery( "#loading-animation").show();
        var termID = jQuery("#parent-term :selected").val();


        jQuery.ajax({
            type: 'POST',
            url: ajaxurl,
            data: {"action": "get_child", parent: termID },
            success: function(response) {
                jQuery("#empty-div-to-load-child-terms").html(response);
                jQuery("#loading-animation").hide();
                return false;

            }
        });
    });
});

You will have to modify your html to match the above code. When the state is selected WordPress will load the child “towns”

Edit

Forgot to mention that the ajaxurl variable in the jQuery will not be defined. Read up on using AJAX in plugins to get the method along with some other useful information.

Leave a Comment