Sometimes we need to have ajax in wordpress element in order to retrieve sub-categories, or anything. To allow using ajax, this several steps can make it happen.
- Add below code under the
functions.phpfile inside theme folder.
[code lang=”php”]
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 .= ‘</option>’;
}
echo ‘<option value="" selected="selected">Select Model</option>’.$option;
die();
} // end if
}
add_action(‘wp_ajax_my_special_action’, ‘implement_ajax’);
add_action(‘wp_ajax_nopriv_my_special_action’, ‘implement_ajax’);//for users that are not logged in.
[/code]
main_catidis the query pass from javascript - On the front end, just create default ajax javascript that has query
man_catidandactionthat assigned tomy_special_actionthat is fromadd_action('wp_ajax_[<action name>]', 'implement_ajax');