How To Update A File After New Post Or Page In WordPress

Looking to update a text file after a new post or page creation in WordPress? All you may need is to add in this function to record the data in a text file.

Recording new post or page permalink in a text file

To record a new post or page permalink in a text file, you must copy and paste the function below into your theme’s functions.php file.

  1. Navigate to Appearance > Editor > Theme Functions (functions.php) from your WordPress website’s dashboard;
  2. Copy and paste in the function below;
  3. Click Update File to save the changes;
  4. Create the records.txt file in your WordPress theme’s directory;
  5. To test, simply create a new post or page in WordPress and view this text file.
function custom_update_txt_file( $post_id ) {
     $post_url = get_permalink( $post_id ) . "\r\n";
     $fp = fopen( get_template_directory() . '/records.txt', 'a' );
     fwrite( $fp, $post_url );
     fclose( $fp );

add_action( 'publish_post', 'custom_update_txt_file' );
add_action( 'publish_page', 'custom_update_txt_file' );

Remember to use “\r\n” and not ‘r\n’ when writing new lines (notice the double quotation marks).