简体   繁体   中英

No hook for new order on woocommerce in a plugin

I tried about 5 hooks to get the order hook for completed and the function doesn't run at all but woocommerce_add_to_cart for example is working!

1. woocommerce_order_status_changed

2. woocommerce_new_order

I just make the alert to know if the function runs but the fucntion is quite large and I make order manullay as a test before deploying the plugin in this function in the plugin in index.php

    function SP_order_token($order_id)
    {
    
    
    ?>
        <script>
            alert("hello");
            alert('<?php echo $order_id; ?>');
        </script>
        <?php
        echo "hello";
    
        global $woocommerce, $post;
  
      
        echo $order_id;
    
        $order =    wc_get_order($order_id);
    
        $order_data = $order->get_data(); // The Order data
    
        var_dump($order_data);
     }
// the final hook is when an order successfully paid
        add_action('woocommerce_order_status_changed', 'SP_order_token',10,1);

Please replace with this and check again.

function woo_order_status_change_custom_check($order_id) {

    ?>
    <script>
        alert("hello");
        alert('<?php echo $order_id; ?>');
    </script>
    <?php
    
    // echo "hello";

    $order = new WC_Order( $order_id );
    $orderstatus = $order->status;

    var_dump($orderstatus);

}

add_action('woocommerce_order_status_changed', 'woo_order_status_change_custom_check', 10, 1);

Your approach for debugging php is wrong. You can't alert or do JS things on the server side. Also, var_dump and echo will work but you don't know where they gonna echo or dump the output.

The correct way for php debugging will be to write your output in external files or in error logs. but I prefer writing in files on the root of wordpress.

Here is the code snippet that you can use:

function sp_order_token( $order_id ) {
    $order = wc_get_order( $order_id );
    $order_data = $order->get_data();

    /**
     * We're using file_put_contents to create a debug.txt file in the root of wordpress where your wp-config.php exists.
     * 
     * we're also passing true in print_r so that print_r returns the output instead of printing it during code execution.
     * 
     * ABSPATH is a constant of wordpress root defined by core WordPress.
     */
    file_put_contents( ABSPATH . 'debug.txt', print_r($order_data, true ) );
}
add_action( 'woocommerce_order_status_changed', 'sp_order_token', 10, 1 );

Once your action will run in wordpress root you'll find debug.txt with your expected output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM