当我在WP中保存帖子时,我需要写入文件。这只是一个基本的例子 - 我将向此文件写入一堆其他内容,而不仅仅是日期。 话虽如此,这个基本示例不起作用。设置绝对路径也无济于事。
update_post_meta只是为了验证函数是否确实运行。
function add_info() {
$date = date('Y-m-d H:i:s');
$file = "latest.json";
file_put_contents($file, $date);
update_post_meta( $post_id, 'latest', $date );
}
add_action( 'save_post', 'add_info', 10, 3 );
此外,"save_post"和"post_updated"都不起作用,但"after_setup_theme"起作用。
事实证明,我需要返回服务器根目录的绝对路径:
$file = ABSPATH . 'latest.json';
或
$file = WP_PLUGIN_DIR . 'latest.json';
将 $post_id 传递给您的函数
function add_info($post_id) {
$date = date('Y-m-d H:i:s');
$file = "latest.json";
file_put_contents($file, $date);
update_post_meta( $post_id, 'latest', $date );
}