在 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。問題是什么以及如何解決?您的幫助將不勝感激。
提前致謝。
uj5u.com熱心網友回復:
錯誤不在鉤子本身!這是您定義日志檔案路徑的方式。
有幾種方法可以做到這一點。
以下代碼是我個人的偏好,因為我認為它更靈活,更易讀:
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和 Woocommerce上進行了測驗,并且運行5.8良好!
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/323229.html
標籤:php WordPress的 求购 打开 钩子商务
