How to directly insert the content of a post in Wordpress to your file manager?

Viewed 625

Let's say a have a file called "hello.txt" on my computer, which holds the content of a new blog post and I do not want to use the WordPress editor for posting! To which folder would I have to upload this text file in order to use it as a new post? When uploaded, can I then directly add this post to the data base or would you rather use php (wp_insert_post()) to transfer the data to the data base?

Thank you for any help.

3 Answers

I don't think you would be able to easily make it automatic, but if you dont mind a little grunt work, you can set up something pretty nice. Here is how i would handle this problem, hope it gets you on the right path.

**** CODE PLACEMENT

  • PHP: Add to your functions.php file
  • HTML/CSS: Add to any page template that only admin can access
  • JS: Add to either an enqueued script file, or in the footer
  • Text file: Create a folder in the root of your theme called post-text-files and upload your text files there

**** THE CODE

Your PHP function would look like this:

// Add your ajax function
add_action("wp_ajax_add_post_from_file", "add_post_from_file");
add_action("wp_ajax_nopriv_add_post_from_file", "add_post_from_file");
function add_post_from_file()
{
    // Set the server path to your file location
    $path = get_stylesheet_directory() . "/post-text-files/";
    // Get list of files from folder
    $files = array_values(array_diff(scandir($path), array('.', '..')));
    // Check if folder is not empty
    if(is_array($files)){
        // Create array variable to use in ajax response
        $new_posts = [];
        // Loop over list of files
        foreach($files as $file){
            // Get post title from filename
            $title = str_replace(".txt","",$file);
            // Check if post already exists
            $duplicate = post_exists($title);
            if($duplicate){
                // If post title exists add ID to response array
                // You can add more logic here to handle the duplicate post title
                $new_posts[] = "Post exists. ID: ".$duplicate;
            } else {
                // Set up args for new post
                $args = [
                    "post_title" => str_replace(".txt","",$file),
                    "post_content" => nl2br(file_get_contents($path.$file)),
                    'post_status' => 'publish'
                ];
                // Add new post and save ID to response array
                $new_posts[] = wp_insert_post($args);
            }
            // Delete the file
            unlink($path.$file);
        }
        // Return response array
        die(json_encode($new_posts));
    }
}

And the front end code like this:

$("#update-posts").click(function() {
  const el = $(this);
  $.ajax({
    type: "post",
    dataType: "json",
    url: "https://httpbin.org/anything",
    data: {
      action: "add_post_from_file"
    },
    success: function(response) {
      console.log(response);
      el.removeClass("active error").addClass("active").text("Added!");
    },
    error: function(xhr, status, error) {
      console.log(xhr);
      console.log(status);
      console.log(error);
      el.removeClass("active error").addClass("error").text("Error");
    }
  })
})
body,
html {
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
  background: slategray;
  min-height: 100%;
}

#update-posts {
  appearance: none;
  -webkit-appearance: none;
  border: none;
  outline: none;
  background: DodgerBlue;
  color: white;
  padding: 12px;
  cursor: pointer;
}

#update-posts:hover {
  transform: scale(1.05)
}

#update-posts.active {
  background: Aquamarine;
  color: LightSlateGrey;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="update-posts">Update Posts</button>

WordPress cannot automatically ingest a text file, converting it to a post. You would need to write a custom script to extract the file contents and store them in the WP database.

You could set up a cron schedule for every x minutes to run a process that would check a designated folder where you intend to FTP your new text files, and then insert them to the database using the wp_insert_post() function: https://developer.wordpress.org/reference/functions/wp_insert_post/

After processing you could either delete the file, move it to a "processed" folder, or alter the name to indicate that it has been processed.

Okay. I do not think using cron would be necessary but I will keep it in mind. Let's say I have

$my_post = array(
    'post_title'    => 'My post',
    'post_content'  => 'Hello World',
    'post_status'   => 'draft',
    'post_author'   => 1,
    'post_category' => array(10)
);
 
wp_insert_post( $my_post );

Where do I even put this code snipped? When I placed this in my "functions.php", it created 20 or more identical posts. It also feels a bit clunky to do this every single time I want to post a new article.

Related