Moh*_*our 3 php wordpress fopen woocommerce hook-woocommerce
在 WooCommerce 中,我\xe2\x80\x99m 尝试在发布产品时触发操作,但它\xe2\x80\x99t 不起作用,这是我的代码:
\nadd_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}\nRun Code Online (Sandbox Code Playgroud)\n这里我\xe2\x80\x99m 尝试创建一个文件并在其中放入一些文本。但正如我所说,该文件并未创建\xe2\x80\x99。
\nI\xe2\x80\x99m 使用 WordPress 5.8.1 和 Woocommerce 5.8.0。问题是什么以及如何解决?我们将非常感谢您的帮助。
\n提前致谢。
\nbug 并不在钩子本身!这是您定义日志文件路径的方式。
做这件事有很多种方法。
以下代码是我个人的偏好,因为我认为它更灵活且更具可读性:
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)
笔记:
$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,并且运行良好!
| 归档时间: |
|
| 查看次数: |
159 次 |
| 最近记录: |