在WooCommerce中,我试图在产品发布时触发一个动作,但它不起作用,这是我的代码:
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 );
}
这里我试图创建一个文件,并把一些文本在它。但是就像我说的,文件没有被创建。
我使用wordpress 5.8.1和Woocommerce 5.8.0。问题是什么?如何解决?非常感谢您的帮助。
提前感谢。
错误不在钩子本身!它是在您定义日志文件路径的方式中。
有几种方法可以这样做。
下面的代码是我个人的偏好,因为我认为它更灵活,更易读:
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);
}
}
注意:
- 我将文件命名为"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);
}
这两个解决方案已经在wordpress5.8.1
和Woocommerce5.8
上进行了测试,并且工作良好!