Last active
January 30, 2018 05:12
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Khalid please help me
I am not able to use this plugin.
Can you please help me on teamviewer