I've added a button to the Woocommerce order page
//function to add button
function action_woocommerce_order_create_csf_order_button( $order ){
echo '<button type="button" class="button" name="create-order-csf">' . __( 'Create CSF Order', 'csf-delivery' ) . '</button>';
};
// add new button for woocommerce
add_action( 'woocommerce_order_item_add_action_buttons', 'action_woocommerce_order_create_csf_order_button', 10, 1);
The result is the following:
Results of executing the Above Code
When the button is clicked it should trigger function which would make a call to an external API.
I've searched what feels like the entire web and cannot figure out how to trigger a php function using this button. I'm new to plugin development and any assistance would be appreciated.
EDIT:
So based on the comments below I would need to listen for the button click using Javascript and trigger the php function using that.
I would appreciate some direction in doing this.
My Answer:
To listen for a button click in JavaScript and trigger a custom PHP function in WordPress, you can use AJAX. Here's a general outline of how you can achieve this:
1. Add a button to the WooCommerce order page using the `woocommerce_order_create_csf_order_button` function.
2. Add a JavaScript function that listens for a click event on the button and sends an AJAX request to trigger the custom PHP function.
3. Create a PHP function in your theme's functions.php file that handles the AJAX request and performs the desired action.
Here's an example implementation:
1. Add a button to the WooCommerce order page:
php
function action_woocommerce_order_create_csf_order_button( $order ) {
echo '';
}
add_action( 'woocommerce_order_create_csf_order_button', 'action_woocommerce_order_create_csf_order_button' );
2. Add JavaScript code to listen for the button click event and send an AJAX request:
javascript
jQuery(document).ready(function($) {
$('#custom-button').on('click', function() {
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
action: 'custom_php_function'
},
success: function(response) {
console.log(response);
}
});
});
});
3. Create a PHP function in your theme's functions.php file to handle the AJAX request:
php
function custom_php_function() {
// Perform your custom PHP function here
// For example, you can update the order status
$order_id = $_POST['order_id'];
$order = wc_get_order( $order_id );
$order->update_status( 'completed' );
die();
}
add_action( 'wp_ajax_custom_php_function', 'custom_php_function' );
Make sure to replace `custom_php_function` with the name of your custom PHP function. Also, don't forget to enqueue the JavaScript file that contains the AJAX code using `wp_enqueue_script`.
This is a basic example to get you started. You may need to modify the code to fit your specific requirements.
Rate this post
4 of 5 based on 1272 votesComments