Run a function on custom button click in woocommerce admin order page
There are some missing things in your code and an error in your last function where count(couriers);
need to be instead count($couriers);
.
// Display an action button in admin order list headeradd_action( 'manage_posts_extra_tablenav', 'admin_order_list_top_bar_button', 20, 1 );function admin_order_list_top_bar_button( $which ) { global $pagenow, $typenow; if ( 'shop_order' === $typenow && 'edit.php' === $pagenow && 'top' === $which ) { ?> <div class="alignleft actions custom"> <button type="submit" name="import_courier" style="height:32px;" class="button" value="yes"><?php echo __( 'Import Couriers', 'woocommerce' ); ?></button> </div> <?php }}// Trigger an action (or run some code) when the button is pressedadd_action( 'restrict_manage_posts', 'display_admin_shop_order_language_filter' );function display_admin_shop_order_language_filter() { global $pagenow, $typenow; if ( 'shop_order' === $typenow && 'edit.php' === $pagenow && isset($_GET['import_courier']) && $_GET['import_courier'] === 'yes' ) { ## -------- The code to be trigered -------- ## update_shipping_couriers_meta_field(); ## -------------- End of code -------------- ## }}// Your function that will be triggered on button pressfunction update_shipping_couriers_meta_field() { $dir = __DIR__; $couriers = file( $dir . '/import-couriers.csv', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES ); $count = count($couriers); $i = 1; do { if ( ! empty( $couriers ) ) { foreach ( $couriers as $a ) { if ( ! empty( $a ) ) { $rows = explode(';', $a); update_post_meta( intval($rows[0]), '_shipping_couriers', $rows[1] ); } $i++; } } } while ( $i <= $count );}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
Based from: Add a button on top of admin orders list in woocommerce