php - 写入文件在functions.php中不起作用 - Wordpress
问题描述
我想在 Wordpress 中创建函数,它将最新帖子的标题写入文件,但找不到有效的代码组合。钩子对吗?我究竟做错了什么?该文件位于主目录中。
我试图将文件放在其他目录中,谷歌向我展示的所有内容都是这样的:bloginfo('template_directory') ?>/new_post_check.txt
add_action('publish_post' , 'alert_new_post');
function alert_new_post(){
$path = 'new_post_check.txt';
file_put_contents( $path, "a" );
}
没有错误消息。
解决方案
试试这个代码,请注意正在写入的文本文件位于 wordpress 安装的根目录中,每次发布帖子时都会覆盖它,因此它只有一个最后发布的帖子的标题:
add_action('publish_post', 'alert_new_post', 10, 2);
function alert_new_post($ID, $post){
$path = 'new_post_check.txt';
file_put_contents($path, $post->post_title);
}
如果您想继续追加到列表中,并将最新发布的帖子添加到列表中,那么您首先必须读取文件的输入,如下所示:
add_action('publish_post', 'alert_new_post', 10, 2);
function alert_new_post($ID, $post){
$path = 'new_post_check.txt';
$post_titles = file_get_contents($path);
// Append a new title to the file
$post_titles .= $post->post_title."\n";
file_put_contents($path, $post_titles);
}
推荐阅读
- python - Python中考虑邻域的条件掩码
- sql-server-2008 - 在 SQL Server Management Studio 中查看作业的 SQL 代码
- python - Tkinter 按钮命令功能不执行其任务
- django - 避免在 Django admin 中使用外键重复查询 __str__()
- vue.js - V-model 更新所有实例
- java - 使用 HTML jQuery 和 Java 在 mySQL DB 中存储 PDF
- amazon-web-services - boto3 iot-data 发布的消息未收到
- d3.js - D3 Sankey Diagrams:如何处理动态数据?没有值(或 0 值)的 IE 节点/链接
- python - ord('q') 和 0xFF 的用法
- java - 我将如何传递原语而不是数组指针