How to use wordpress functions in an ajax call

前端 未结 3 1418
既然无缘
既然无缘 2020-12-24 09:02

I wanted to know if there is a way to use function like query_post() in an ajax call ?

Let\'s say i\'m calling the file _inc/ajax.php

I want to be abble to

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-24 09:56

    WordPress provides an Ajax Url that you should use along with a complete Ajax API.

    You need to create a jQuery function.

    Example:

    jQuery(document).ready(function($) {
    
        var data = {
            action: 'my_action',
            whatever: 1234
        };
    
        jQuery.post(ajaxurl, data, function(response) {
            alert('Got this from the server: ' + response);
        });
    });
    

    The ajaxurl var is always available on the admin side. If your using it on the front end you need to define it.

    Then a PHP function where you can run your query. The PHP function must get attached to the wp_ajax_your_action action.

    Example:

    add_action('wp_ajax_my_action', 'my_action_callback');
    
    function my_action_callback() {
        global $wpdb; // this is how you get access to the database
    
        $whatever = intval( $_POST['whatever'] );
    
        $whatever += 10;
    
            echo $whatever;
    
        die(); // this is required to return a proper result
    }
    

    The wp_ajax_your_action action is for admin if you need to use it on the front end the action would be wp_ajax_nopriv_your_action

提交回复
热议问题