Skip to content

Instantly share code, notes, and snippets.

@khaledsaikat
Last active January 30, 2018 05:12
Show Gist options
  • Save khaledsaikat/5925ff1fb5a2e53dfd02 to your computer and use it in GitHub Desktop.
Save khaledsaikat/5925ff1fb5a2e53dfd02 to your computer and use it in GitHub Desktop.
Frontend AJAX Sub-Category Dropdown (Load sub-category dropdown based on parent category by ajax call)
<?php
/*
Plugin Name: Frontend AJAX Sub-Category Dropdown
Plugin URI: http://khaledsaikat.com
Description: Load sub-category dropdown based on parent category by ajax call
Version: 0.1
Author: Khaled Hossain
Author URI: http://khaledsaikat.com
*/
/**
* Add shortcode [ajax-dropdown] to any post or page
*/
if ( ! class_exists( 'frontendAjaxDropdown' ) ):
class frontendAjaxDropdown
{
/**
* Loading WordPress hooks
*/
function __construct()
{
/**
* Add shortcode function
*/
add_shortcode( 'ajax-dropdown', array($this, 'init_shortocde') );
/**
* Register ajax action
*/
add_action( 'wp_ajax_get_subcat', array($this, 'getSubCat') );
/**
* Register ajax action for non loged in user
*/
add_action('wp_ajax_nopriv_get_subcat', array($this, 'getSubCat') );
}
/**
* Show parent dropdown for wordpress category and loaded necessarry javascripts
*/
function init_shortocde()
{
wp_dropdown_categories(
'name=main_cat&selected=-1&hierarchical=1&depth=1&hide_empty=0&show_option_none=All Categories'
);
?>
<script type="text/javascript">
(function($){
$("#main_cat").change(function(){
$("#sub_cat").empty();
$.ajax({
type: "post",
url: "<?php echo admin_url( 'admin-ajax.php' ); ?>",
data: { action: 'get_subcat', cat_id: $("#main_cat option:selected").val() },
beforeSend: function() {$("#loading").fadeIn('slow');},
success: function(data) {
$("#loading").fadeOut('slow');
$("#sub_cat").append(data);
}
});
});
})(jQuery);
</script>
<div id="loading" style="display: none;">Loading...</div>
<div id="sub_cat"></div>
<?php
}
/**
* AJAX action: Shows dropdown for selected parent
*/
function getSubCat()
{
wp_dropdown_categories(
"name=sub_cat&selected=-1&hierarchical=1&depth=1&hide_empty=0&child_of={$_POST['cat_id']}"
);
die();
}
}
endif;
new frontendAjaxDropdown();
@abhi2095
Copy link

Khalid please help me
I am not able to use this plugin.
Can you please help me on teamviewer

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment