Add action button and "controller" to order list (admin) - WooCommerce

Viewed 67

For several hours I'm trying to add an action button with the "controller" part to receive the request.

I've tried to add a real "action button" but it doesn't work. I tried many ways from many StackOverflow posts, but it doesn't work.

So, I added a link to a custom column:

add_filter( 'manage_edit-shop_order_columns', 'custom_set_order_columns' );
function custom_set_order_columns($columns){
    $new_columns = (is_array($columns)) ? $columns : array();
    unset( $new_columns['order_actions'] );
        unset( $new_columns['order_total'] );

    $new_columns['test_button'] = 'Test';
    $new_columns['order_actions'] = $columns['order_actions'];

    return $new_columns;
}

Set the column value:

add_action( 'manage_shop_order_posts_custom_column', 'custom_set_order_column_values', 2 );
function custom_set_order_column_values($column){
    global $post;

    $order = wc_get_order( $post->ID );
    $email = $order->get_billing_email();
    $admin_ajax_url = admin_url("admin-ajax.php");

    $link_btn = "<a href='#' class='button button-primary' onclick='start(\"$email\",\"$admin_ajax_url\")'>Start</a>";
    
  if ( $column == 'test_button' ) {
    echo $link_btn;
  }
}

JS part:

function start(email, adminAjaxUrl) {
  jQuery.ajax({
      url : adminAjaxUrl,
      type : 'POST',
      data : {
          action : 'test_button_post',
          param1: email
      },
      success : function( response ) {
        var success = JSON.parse(response)['success'] == "true";
        if (success) {
          jQuery('#wpbody-content .wrap ul').before('<div class="notice notice-success"><p>' + response['message'] + '</p></div>');
        } else {
          jQuery('#wpbody-content .wrap ul').before('<div class="notice notice-info"><p>' + response['message'] + '</p></div>');
        }
      }
  });
}

WP AJAX

add_action( 'wp_ajax_test_button_post', 'test_button_post' );
function test_button_post() {
  if (!($_SERVER['REQUEST_METHOD'] === 'POST')) {
    die();
  }

  $response['success'] = "true";
  $response['email'] = $_REQUEST['param1'];
  $response['message'] = "some message";
  echo json_encode($response);
  die();
}

As I don't use WordPress/WooCommerce often, it seems difficult for me. I don't need the AJAX POST. I would like to know a way to add a real button in the orders list, and after a click on the button, the request goes to a method like the "test_button_post()", and inside that method I render the notice message and the page redirect automatically.

Something like:
Button click -> test_button_post method (to act as a controller) and redirect to display the notice message.

In the test_button_post method I need to get the params and make a request to an external API, and then display the result.

I don't know if it is the right way to do that.

WordPress Version: 5.5
WooCommerce Version: 4.4.1

0 Answers
Related