Export all posts as individual plain txt files

Try this (you may need to bootstrap WP by loading wp-load.php, depending on where you put this code).

$args = array(
    'post_type' => 'post',
    'post_status' => 'publish',
    //'posts_per_page' => -1 //uncomment this to get all posts
);

$query = new WP_Query($args);
while ( $query->have_posts() ) : $query->the_post();
    $f = fopen(get_the_title() . '.txt', 'w');
    $content="Title: " . get_the_title() . PHP_EOL;
    $content .= 'Pub date: ' . get_the_date() . PHP_EOL;
    $content .= 'Category: ';
    foreach (get_the_category() as $cat) {
        $content .= $cat->cat_name . ', ';
    }       
    $content .= PHP_EOL . PHP_EOL;
    $content .= get_the_content();

    fwrite($f, $content);
    fclose($f);
endwhile;

Keep in mind, if two posts have the same title, you’ll only get one text file.

Leave a Comment