How to Create WordPress Posts in Themes/Plugins
96Recently, one of our clients needed to let visitors create WordPress posts (Or custom post types of course) from the website itself.
In this post, I’m going to walk through some of the WordPress functions I used to achieve this. We’ll go over creating the post itself, adding categories/tags, and adding metadata.
(We’ll skip the stage where you build a form, validate what users enter etc. and just focus on the WordPress functions instead)
Create the Post
The method to create the core post is simple. Essentially, you build a $post object, and then insert it with wp_insert_post().
You can use our $post reference to speed this up. Let’s take a look at some examples:
1 2 3 4 5 6 | $new_post = array( 'post_title' => 'Our New Post', 'post_content' => 'Our filler text for the post.' ); $post_id = wp_insert_post($new_post); |
That would create a new post, with the title “Our New Post”, and the filler text we’ve entered.
If wp_insert_post() is successful, it returns the ID of the new post it has created (Which we assign to $post_id here). If it fails, it will return 0.
By default, the status is set to “Draft”, so let’s tweak it to publish the post instantly:
1 2 3 4 5 6 7 | $new_post = array( 'post_title' => 'Our New Post', 'post_content' => 'Our filler text for the post.', 'post_status' => 'publish' ); $post_id = wp_insert_post($new_post); |
You can set just about any value from the $post variable, e.g.
1 2 3 4 5 6 7 8 9 10 | $new_post = array( 'post_title' => 'Our New Post', 'post_content' => 'Our filler text for the post.', 'post_status' => 'publish', 'post_type' => 'page', 'post_author' => 2, 'post_date' => '2011-09-01 15:10:30' ); $post_id = wp_insert_post($new_post); |
Our post is now a page, written by user #2, and scheduled to be published on the 1st of September.
Categories, Tags and Custom Taxonomies
Let’s move on to categories and tags. You can either set these as you make the rest of the post, or add them separately later. Let’s start by seeing how it is done in wp_insert_post().
For categories, you pass in an array containing the IDs of the categories you want to add, e.g. for categories 9 and 29:
1 2 3 4 5 6 7 8 | $new_post = array( 'post_title' => 'Our New Post', 'post_content' => 'Our filler text for the post.', 'post_status' => 'publish', 'post_category' => array(9, 29) ); $post_id = wp_insert_post($new_post); |
Tags are a little easier. Instead of passing in the IDs, you can use the names of the tags themselves, e.g.
1 2 3 4 5 6 7 8 | $new_post = array( 'post_title' => 'Our New Post', 'post_content' => 'Our filler text for the post.', 'post_status' => 'publish', 'tags_input' => array('tag1', 'Filler Tag') ); $post_id = wp_insert_post($new_post); |
You can even set the terms of a custom taxonomy. This uses the “tax_input” parameter and expect you to give it an array where each key is a custom taxonomy, and each value is an array of tags in that taxonomy.
Update (8 Aug 2011): Rarst has left a comment saying that “tax_input” will only work if initiated by a logged in user with the permission to edit that taxonomy. If this affects you, read on below for a different solution that will work anywhere!
For example, let’s say we have a taxonomy called “custom_tax”, and the two tags we want to add to the post are “Dolor” and “Ipsum”.
1 2 3 4 5 6 7 8 9 10 | $new_post = array( 'post_title' => 'Our New Post', 'post_content' => 'Our filler text for the post.', 'post_status' => 'publish', 'tax_input' => array( 'custom_tax' => array('Dolor', 'Ipsum') ) ); $post_id = wp_insert_post($new_post); |
I mentioned that you could also add your tags later on. To do that, use the wp_set_object_terms() function (There are similar functions to this one, specifically for tags etc. but this covers it all for you).
The format is: wp_set_object_terms( post ID , array of tag IDs , taxonomy , append true/false ).
The last value is important. If you set true, then your new tags will be added to any existing ones. If you set false, then any existing tags will be replaced with your new ones.
Here are some examples of adding categories, tags, and a custom taxonomy this way:
1 2 3 | wp_set_object_terms( $post_id, array(27, 28, 29), 'category', true); wp_set_object_terms( $post_id, array('Example', 'Lorem Ipsum'), 'post_tag', true); wp_set_object_terms( $post_id, array('Lorem', 'Sit'), 'custom_tax', true); |
Metadata
If you’ve ever added custom meta data to a post before, you know what to do already.
Let’s say we want to add a custom field with the name “summary” and the value “Quick Summary!”:
1 | add_post_meta( $post_id, 'summary', 'Quick summary!', true); |
That’s quite self-explanatory. The ‘true’ at the end refers to whether this field is unique or not. If we set this to false, and a summary already exists, then another custom field also titled ‘summary’ would be added to the post.
By setting it to true, this won’t happen. WordPress checks for the ‘summary’ field first, and if it exists, it does nothing (You would then need to use update_post_meta() instead).
One special note to make is that if you want to set a page template, you do this with the meta functions as well. WordPress stores the name of the template file to use in a custom field titled ‘_wp_page_template’
1 | update_post_meta( $post_id, '_wp_page_template', 'onecolumn-page.php'); |
Between those functions, you should be able to set up any post data you need. Feel free to post in the comments if you have any questions, or I’d love to hear how you’ve allowed users to add content to a WordPress site!
Enjoy this post? You should follow me on Twitter!
Note on using tax_input – it will check for user capabilities for custom taxonomy and so will fail if you inserting is done by non-user, in cron task or whatever.
So, unless only registered and logged in users are going to be using that, it is unreliable.
Thanks for the tip Rarst! I’ve only used it in the context of a logged in user (Not on purpose), so hadn’t hit that issue.
I’ve updated the post now with a note about this. For anyone it would affect, they can then use the alternative solution.
Thanks for letting me know!
Thanks Michael, brilliant solution.
Excellent Michael. You may recall me asking you about a bug I was having with wp_set_object_terms(). The tax_input parameter of wp_insert_post() is new to me and may solve the problem :)
It was new to me too. It was only recently that I had cause to drill down deeper in wp_insert_post() and came across this. Quite handy it seems! :)
Thanks for the comment Pippin!
So far I think there are not any plugins available to let users create posts. Only problem i am afraid of is spam content generation, code exec or any security loop holes. anyway a much useful code.
That’s very true, the bulk of the work here definitely comes in setting up the form and validating the data.
On one of the sites, we used a range of measures to fight the spam. Logged in authors can publish straight away, but everyone else’s post is saved as a draft and there’s a notification at the top of the dashboard with the number of drafts awaiting approval for editors.
Visitors also need to fill out a reCaptcha as part of the form.
Only went live very recently though, so need some more time to tell how effective its all been!
You have done many thing to control spam and looks sufficient. How about releasing this as a plugin?
Would take a good bit more work to make it applicable to everyone though. The nature of this code is that if you’re making posts in your theme/plugin, you’re most likely doing something quite specific to your particular script.
It’s the sort of thing developers could get great use from, but I’m not sure a plugin for mass users would do them too much good (Unless it was made into something quite generic, like a form for accepting regular post submissions on site?)
Code injection is always a question and with changing in wordpress core sometimes there are doors left opened. Personally I trust in in htaccess filtering and if you are not on shared hosting snort does a good job as this remains there for good when wordpress upgrades.
Thanks you very much. This article very useful for me. Because i am learning wordpress and have any problem. But when i read this article, i knew problem of me. Thanks again.
I began using WordPress as well, an trying to get as many helpful tools that can help with first, getting visitors into my blog, and second, controlling the comment environment, gathering them all to achieve the best WordPress blog there is.
I appreciate all of your help… As a non-computer guy trying to figure out and run a blog, I would be completely lost without all of your help…
I’m also getting deeper into wordpress by encouraging myself by these web development articles. Thanks Michael
Thank you for this great article. As a designer, I really appreciate these tips.
Patrick Sharp Jersey For Sharp Fans.
Thanks you very much. This article very useful for me. Because i am learning wordpress and have any problem. But when i read this article, i knew problem of me. Thanks again.
testing
Love this wordpress tutorial! It was very helpful! Thank you for taking the time to do all of that.
That’s awesome collection but my favorite is “Look”
I appreciate the tips you shared. I love blogging and I hope the ideas I learned will make me more efficient when performing such task.
Its an interesting post, I like wordpress because it is truly user friendly. I like the fact that I don’t have to be a geek to work on wordpress. Some of the themes I’ve come across are amazing and creating posts in themes sounds even more challenging.
My friend is a great article taken off again. 1-2 times a month I look at your website. And do your own changes to my website.
Incredible tips you gave.
its great to see that you’ve suggested custom taxonomy as they are a great function. some nice steps to follow and would have been good to see some query_posts added for good measure.
its great to see that you’ve suggested custom taxonomy as they are a great function. some nice steps to follow and would have been good to see some query_posts added for good measure.
http://avoo.net/fxrya
You are the problem solver, i have come across with a problem to customizing my posts on my blog and i am helpless and don’t have any way to get rid of it, glad to come across with your blog. Thanks so much.
Thanks for compratir, has helped me a lot
For me doesn’t work ((((
it is a long time not visit your blog, but still no new post here.
You can also donate items to charity. In short, you can pare down the contents of the attic quickly.
Thanks for this really usefull tutorial !
Nice sort of tips, it will be useful when i need to do this on wordpress. Really need that tip. Thanks
WordPress is efficient blogging tool and also it is easy to manage, these types of Plugins are helpful to bloggers for customize WordPress blog, nice post thanks for share
oh. I think I have to learn coding :(
oh, nice site yar
Thanks for this really usefull information
it doesn’t work on me. whew!
I’ll try again, gotta research more on where I’ve gone wrong. Maybe the syntax in a certain area.
nice sharing. it will surely help me themes, plugins in WordPress Posts
I’ve been looking for some kind of solution to this for ages for one of my sites. I’ll give it a go.
easy and useful
thanks a LOT
oh. I think I have to learn coding :(
Welcome to Snapbackhatsaler.com, where you will find so many surprises on our hats.We Have Huge Range Of Snapback Hats. Cheap NFL, MLB, NBA, Soccer Snapbacks At Unbelievable Prices From Factory Directly.
hmmm nice tps gan.. Thanks for share
It really gives a great idea. That was very interesting post.
Nice to be visiting your blog again
yes, i got it now how to make it…
thanks my friend about this post, i’m willing to follow this tutor,,
Didn’t know that it’s possible to achieve this in so simple way. I had to do similar thing some while ago but just gave up my effort as it wasn’t critically important.
vry informative article..
Previously I was unable to work in wordpress due to complicated outlook and using Blog Spot. But now i hope im comfortable to work on it…
thanx for ur sharing…
this is really useful! thanks
http://cellphoneview.net/samsung-galaxy-ace-hugo-boss-offers-a-simplicity-and-sophisticated-design-on-phonehouse.html
Impressive! Thanks for sharing !
Very nice n impressive tutorial, Having nice skills :)
its an interesting post, I like wordpress because it is truly user friendly. I like the fact that I don’t have to be a geek to work on wordpress. Some of the themes I’ve come across are amazing and creating posts in themes sounds even more challenging.
Thanks for posting Michael –
I couldn’t see anything in the article itself about ‘moderating’ or saving as Draft for the visitors’ posts – then I saw your comment further down – good idea indeed ;-)
Many Thanks,
Darren.
Certainly this is a effective article to create posts in wordpress theme or plugins. Moreover, the writer has added some essential information. In this sense this article is informative too.
thank you soo much admin..
I couldn’t see anything in the article itself about ‘moderating’ or saving as Draft for the visitors’ posts – then I saw your comment further down – good idea indeed ;-)
As i am new for using blogs, i found using plugins to wordpress,a difficult one. Thanks for sharing this. Let me try this one:)
Just clipped this to my Evernote account. Definitely one for the future so thank you. Have been thinking about creating a front end guest posting site for a while now.
Tar Very Much
Great tutorial, easy to understand and it was just what I needed. Thanks heaps
This is great Well thought out thanks
They want to be shielded, protected, and given their own way, petted by the world, so that no breath of opposition adds to the problems of life.
Great tutorial. I like it because it is detailed and you’ve included screen shots that made it much easier to understand. I would recommend your blog for people who are looking to learn WordPress.
parent has less experience and knowledge about how to educate and supervise children
Great Article, helped a lot!
Its an usefull interesting post, I love wordpress because it is truly user friendly. I like the fact that I don’t have to be a geek to work on wordpress. Some of the themes I’ve come across are amazing and creating posts in themes sounds even more challenging.
easy to follow, nice to learn, thanks for sharing
Nice tutorial thank you so much it helped me a lot :)
This is great information. Thank you for spelling every thing out. And, happy New Year.
Its a great and useful tips advices shared. Keep posting and do stay in touch with more informative posts like this.
Really it’s very good post. Knowledge sharing is the optimum result of knowledge gaining. You are a good reader and also a knowledge seeker .Keep it up.
Great Site! Nice to see it all available in one; keep it u
Good Tutorial. It was very useful
Thank you very much. great post
Cool, easy to learn and very useful.
thanks for share it!
I just found out this way from you
thank you
Thank you for the useful information. I am still learning WordPress, and it can be very frustrating if you are new to it. I find your site very helpful and look forward to returning.
Discount designer sunglasses with distinguished design and top quality available at Sunglassessale.biz.<a
Really nice post once again, thanks for sharing.
its great to see that you’ve suggested custom taxonomy as they are a great function.
Some helpful functions, this could help me.
wordpress did not know that could be edited so it is very good as well as more projects can be tailored to my needs
Thnx Dude
top songs
Really nice post once again, thanks for sharing.. This article very useful for me. Because i am learning wordpress and have any problem. But when i read this article, i knew problem of me. Thanks again.
Incredible tips you gave.
thank you!
Incredible tips you gave.
There is noticeably a bundle to learn about this. I assume you made sure nice points in features also
The information are quite helpful, thanks a lot.
Thanks a bunch mate! your guide led me to wp_set_post_terms which works great with custom taxonomies ;)
this information is very helpful thanxs
Hi,
Actually I need your help to improve my blogging skill because I am new in this field, hence I need your support to make effective blogging.
I also found your posts very interesting. In fact after reading, I had to go show it to my friend and he ejoyed it as well
I do not quite understand about coding
looks like it took a good basic understanding in order to understand how to make a post in wordpress themes
thank you and success always.
Thank You :)
Great tutorial, you guys saved me hours of hard work. So appreciated