programmatically create posts from files in a folder

I have a folder named ‘pdf’ (with around 1000 pdf files) in my uploads directory, i would like to create a post for each file in the folder.

I am not trying to import the content from the pdf but simply create a post for each file in that folder.

What i was hoping to achieve:

the posts would get the title from the filename.

the posts would be assigned a single specific category/tag for all the posts.

the post would get the publish date from the file creation date.

I am new to php, wordpress and programming in general, I have a decent understanding of the syntax, loops and functions. I was hoping someone could give me a nudge in the right direction as to what wordpress functions / php loops would be helpful to achieve this. Any thoughts, guidance, information would be a huge help.

Many thanks for your time and help,
Sam

Solutions Collecting From Web of "programmatically create posts from files in a folder"

At first you have to use readdir() in a while loop to get all pdf files. You should look at the examples on the readdir page to know how to use it.
Inside the loop you have to add the posts with the pdf files. Normally you would use wp_insert_attachment() to add files to your blog. But if you want a single post for each pdf which is shown on your homepage you have to use wp_insert_post(), where the argument “file” contains the path to the file. After adding the post (but also in the loop) you have to use the id, which comes back from wp_insert_post(), you have to add the category using wp_set_post_categories.

I could provide you the whole code to perform this task, but in my opinion it is better to learn it by writing the code yourself. If you have further questions don’t hesitate to ask.