01.
function
parent_child_cat_select() { ?>
02.
<script type=
"text/javascript"
>
03.
04.
jQuery(document).ready(
function
() {
05.
jQuery(
'#parent_cat'
).change(
function
(){
06.
var
parentCat=jQuery(
'#parent_cat'
).val();
07.
08.
jQuery.ajax({
09.
url:
"/wp-admin/admin-ajax.php"
,
10.
type:
'POST'
,
11.
data:
'action=category_select_action&parent_cat_ID='
+ parentCat,
12.
success:
function
(results)
13.
{
14.
jQuery(
"#sub_cat_div"
).html(results);
15.
}
16.
});
17.
});
18.
});
19.
20.
</script>
21.
22.
<form action=
"<?php bloginfo('url'); ?>/"
method=
"get"
>
23.
24.
<div id=
"parent_cat_div"
><?php wp_dropdown_categories(
"show_option_none=Select parent category&orderby=name&depth=1&hierarchical=1&id=parent_cat"
); ?></div>
25.
26.
<div id=
"sub_cat_div"
><select name=
"sub_cat_disabled"
id=
"sub_cat_disabled"
disabled=
"disabled"
><option>Select parent category first!</option></select></div>
27.
28.
<div id=
"submit_div"
><input type=
"submit"
value=
"View"
/></div>
29.
30.
</form>
31.
<?php }
32.
33.
function
implement_ajax() {
34.
$parent_cat_ID
=
$_POST
[
'parent_cat_ID'
];
35.
if
( isset(
$parent_cat_ID
) )
36.
{
37.
$has_children
= get_categories(
"parent=$parent_cat_ID"
);
38.
if
(
$has_children
) {
39.
wp_dropdown_categories(
"orderby=name&parent=$parent_cat_ID"
);
40.
}
else
{
41.
?><select name=
"sub_cat_disabled"
id=
"sub_cat_disabled"
disabled=
"disabled"
><option>No child categories!</option></select><?php
42.
}
43.
die
();
44.
}
45.
}
46.
add_action(
'wp_ajax_category_select_action'
,
'implement_ajax'
);
47.
add_action(
'wp_ajax_nopriv_category_select_action'
,
'implement_ajax'
);
48.
49.
50.
function
load_jquery() {
51.
wp_enqueue_script(
'jquery'
);
52.
}
53.
add_action(
'init'
,
'load_jquery'
);