skip to Main Content

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);

2

Answers


  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);
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search