I’m trying to show the parent categories in a drop-down box and based on which parent categories are selected, their Sub Categories should appear in a separate drop-down box via an ajax call.
I’ve done a lot of research and came across the following article which is 100% what I need to achieve: https://1stwebdesigner.com/implement-ajax-wordpress-themes/
I followed it correctly but for some reason, the sub-category drop-down is always disabled.
My end goal is to have the 2 dropdowns with a submit button and have it act as a search form, display the selected sub-category posts on a separate page, this was my first step to getting there but having no luck.
I’ve tried changing the javascript $ to jQuery as this was giving an error the first time I used it but currently no errors on the page at all.
<!-- Dropdown select box & javascript -->
<div id="content">
<?php
wp_dropdown_categories('show_count=0&selected=-1&hierarchical=1&depth=1&hide_empty=0&exclude=1&show_option_none=Main Categories&name=main_cat');
?>
<select name="sub_cat" id="sub_cat" enabled="disabled"></select>
<script type="text/javascript">
jQuery(function() {
jQuery('#main_cat').change(function() {
var $mainCat = jQuery('#main_cat').val();
// call ajax
jQuery("#sub_cat").empty();
jQuery.ajax({
url: "/wp-admin/admin-ajax.php",
type: 'POST',
data: 'action=my_special_action&main_catid=' + $mainCat,
success: function(results) {
// alert(results);
jQuery("#sub_cat").removeAttr("disabled");
jQuery("#sub_cat").append(results);
}
});
});
});
</script>
</div>
<!-- Ajax call in function.php -->
add_action('wp_ajax_my_special_action', 'my_action_callback');
add_action('wp_ajax_nopriv_my_special_action', 'my_action_callback');
function implement_ajax() {
if(isset($_POST['main_catid']))
{
$categories= get_categories('child_of='.$_POST['main_catid'].'&hide_empty=0');
foreach ($categories as $cat) {
$option .= '<option value="'.$cat->term_id.'">';
$option .= $cat->cat_name;
$option .= ' ('.$cat->category_count.')';
$option .= '</option>';
}
echo '<option value="-1" selected="selected">Scegli...</option>'.$option;
die();
} // end if
}
add_action('wp_ajax_my_special_ajax_call', 'implement_ajax');
add_action('wp_ajax_nopriv_my_special_ajax_call', 'implement_ajax');//for users that are not logged in.