WordPress: Allow Using Ajax Request on Theme

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.

  1. Add below code under the functions.php file 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_catid is the query pass from javascript
  2. On the front end, just create default ajax javascript that has query man_catid and action that assigned to my_special_action that is from add_action('wp_ajax_[<action name>]', 'implement_ajax');

Septu Jamasoka has written 23 articles

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>