Using a do_shortcode in wordpress via an ajax call

2020-07-30 02:25发布

I have the following piece of Ajax which calls a php file which intends to return the HTML content of a shortcode.

The Ajax call looks like this :

 var PostData = "Action=refresh-cart";
                     jQuery.ajax({
                       dataType: "text",
                       type: 'POST',
                       url : '<?php echo plugins_url( 'class-booking-system/class-booking-process.php', dirname(__FILE__) );?>',
                       cache: false,
                       data : PostData,
                       complete : function() {  },
                       success: function(data) {
                         //   jQuery("#loading-img").hide();
                            alert(data);
                           // jQuery("#join-class-div-3").html(data);

                        }           
                });

The PHP looks like this :

<?php
require_once( ABSPATH . '/wp-includes/shortcodes.php' );

if(isset($_POST['Action'])) {
        $Action = $_POST['Action'];
        if($Action == "refresh-cart") {


           echo do_shortcode('[woocommerce_cart]'); 

            }
        }
?>

However when I call my Ajax method it returns an HTTP 500 - which I assume means the do_shortcode function was not found in this context. How can I give my plugin the ability to call this wordpress function via ajax?

1条回答
贪生不怕死
2楼-- · 2020-07-30 03:11

I think you should take a look at the Codex article on using Ajax in Plugins. It provides a very good example on how to go about making ajax calls in WordPress.

Adapting their example to your code I get something like the following:

First we load the javascript. We also pass some javascript variables via wp_localize_script. In this case, we're going to pass the admin's URL for processing all ajax calls.

wp_enqueue_script( 'ajax-script', plugins_url( '/js/my_query.js', __FILE__ ), array('jquery') );

// in JavaScript, object properties are accessed as ajax_object.ajax_url
wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );

Second, in our javascript we can make the ajax call and define our ajax "action" and any other data we need in the data object. Because "action" has kind of a different meaning, I've renamed your action to "refresh_cart".

jQuery(document).ready(function($) {

    $.ajax({
        type: 'POST',
        url : ajax_object.ajax_url,
        cache: false,
        data : { 'action': 'my_action', 'refresh_cart': 'yes' },
        complete : function() {  },
        success: function(data) {
            // $("#loading-img").hide();
            alert(data);
            // $("#join-class-div-3").html(data);
        }
    });

});

Third, we need to set up the callback for our ajax action. admin-ajax.php looks through all of WordPress's pre-configured actions and then also looks for anything added to the wp_ajax_$my_action_name on the back-end and wp_ajax_nopriv_$my_action_name on the front-end. I am assuming your question concerns the front-end and since in the data object we set action = my_action the corresponding action hook would be wp_ajax_nopriv_my_action... to which we have attached the my_action_callback function. WordPress should be fully loaded and their shouldn't be an issue running shortcodes as far as I can tell.

add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );

function my_action_callback() {
    if( isset($_POST['refresh-cart']) && $_POST['refresh-cart'] == 'yes' ) {
        echo do_shortcode('[woocommerce_cart]'); 
    }
    die();
}

And voila! I think that should do it, but I have to warn you that I didn't test any of this, so use with prudence.

查看更多
登录 后发表回答