Search code examples
phpwordpresswoocommercefopenhook-woocommerce

WooCommerce triggering an action and creating a log file when product is published


In WooCommerce, I’m trying to trigger an action when a product is published, but it doesn’t work, here is my code:

add_action( 'transition_post_status', 'my_call_back_function', 10, 3 ); 
function my_call_back_function( $new_status, $old_status, $post ) {
    if (
      'product' !== $post->post_type ||
      'publish' !== $new_status ||
      'publish' === $old_status
   ) {
      return;
   }
   file_put_contents( 'file.txt', 'Product published', FILE_APPEND ); 
}

Here I’m trying to create a file and put some text in it. But as I said, the file isn’t created.

I’m using wordpress 5.8.1 and Woocommerce 5.8.0. What is the problem and how to solve it? Your help would be greatly appreciated.

Thanks in advance.


Solution

  • The bug is not in the hook itself! It's in the way you've defined the path to the log file.

    There are several ways to do this.

    The following code is my personal preference because I think it's more flexible and more readable:

    add_action('transition_post_status', 'my_call_back_function', 10, 3);
    
    function my_call_back_function($new_status, $old_status, $post)
    {
        if (
            'product' !== $post->post_type ||
            'publish' !== $new_status ||
            'publish' === $old_status
        ) {
            return;
        }
    
        $your_custom_file = __DIR__ . '/zzz.txt';
    
        if (!file_exists($your_custom_file)) {
            $file = fopen($your_custom_file, 'w');
            fwrite($file, 'Product published');
            fclose($file);
        } else {
            $file = fopen($your_custom_file, 'a');
            fwrite($file, ',');
            fwrite($file, 'Product published');
            fclose($file);
        }
    }
    

    Note:

    • I named the file "zzz.txt" just to give you an example! Feel free to change its name!
    • $your_custom_file points to the root directory of your theme. Feel free to change it if you would want to save your file in a sub-directory.
    • If your file already exists, then I've put a , to separate the logs. Again feel free to change it!

    Another way using file_put_contents function.

    add_action('transition_post_status', 'my_call_back_function', 10, 3);
    
    function my_call_back_function($new_status, $old_status, $post)
    {
        if (
            'product' !== $post->post_type ||
            'publish' !== $new_status ||
            'publish' === $old_status
        ) {
            return;
        }
    
        $your_custom_file = __DIR__ . '/zzz.txt';
    
        file_put_contents($your_custom_file, 'Product published', FILE_APPEND);
        
    }
    

    Both solutions have been tested on wordpress 5.8.1 and Woocommerce 5.8 and work fine!