我想在Wordpress中创建函数,该函数会将最新帖子的标题写入文件,但找不到有效的代码组合。钩子对吗?我究竟做错了什么?该文件位于主目录中。
我正尝试将文件放入其他目录中,而google向我显示的所有内容如下: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" );
}
没有错误消息。
答案 0 :(得分:0)
尝试此代码,请注意,要写入的文本文件位于wordpress安装目录的根目录中,每次发布时都会被覆盖,因此该文件只有最后发布的帖子的一个标题:< / p>
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);
}