WooCommerce 在发布产品时触发操作并创建日志文件

Moh*_*our 3 php wordpress fopen woocommerce hook-woocommerce

在 WooCommerce 中,我\xe2\x80\x99m 尝试在发布产品时触发操作,但它\xe2\x80\x99t 不起作用,这是我的代码:

\n
add_action( 'transition_post_status', 'my_call_back_function', 10, 3 ); \nfunction my_call_back_function( $new_status, $old_status, $post ) {\n    if (\n      'product' !== $post->post_type ||\n      'publish' !== $new_status ||\n      'publish' === $old_status\n   ) {\n      return;\n   }\n   file_put_contents( 'file.txt', 'Product published', FILE_APPEND ); \n}\n
Run Code Online (Sandbox Code Playgroud)\n

这里我\xe2\x80\x99m 尝试创建一个文件并在其中放入一些文本。但正如我所说,该文件并未创建\xe2\x80\x99。

\n

I\xe2\x80\x99m 使用 WordPress 5.8.1 和 Woocommerce 5.8.0。问题是什么以及如何解决?我们将非常感谢您的帮助。

\n

提前致谢。

\n

Ruv*_*vee 5

bug 并不在钩子本身!这是您定义日志文件路径的方式。

做这件事有很多种方法。

以下代码是我个人的偏好,因为我认为它更灵活且更具可读性:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 我将文件命名为“zzz.txt”只是为了给您一个例子!请随意更改其名称!
  • $your_custom_file指向主题的根目录。如果您想将文件保存在子目录中,请随意更改它。
  • 如果您的文件已经存在,那么我已经用 来,分隔日志。再次随意更改它!

另一种使用file_put_contents函数的方式。

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);
    
}
Run Code Online (Sandbox Code Playgroud)

这两种解决方案都已在 WordPress5.8.1和 Woocommerce上进行了测试5.8,并且运行良好!