首页 > 解决方案 > 写入文件在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" ); 
}

没有错误消息。

标签: phpwordpress

解决方案


试试这个代码,请注意正在写入的文本文件位于 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); 
}

推荐阅读