简体   繁体   中英

Writing to file doesn't work in functions.php - Wordpress

I want to make function in Wordpress, which will write title of newest post to file, but can't find working combine of code. Is the hook right? What am I doing wrong? The file is in main catalog.

I was trying put the file in other catalogs and all the stuff google was showing me like this: 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" ); 
}

No errors message.

Try this code, please note the text file being written to is located in the root of the wordpress install and it will be overwritten each time a post is publish, hence it will only have one title of the last published post:

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); 
}

If you will like to keep appending to the list, with the latest publish post being added to the list, then you will first have to read the input of the file, something like this:

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); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM