Submit WordPress Posts From The Frontend

form

If you’re looking to make adding new posts without having to log into the WordPress dashboard, or maybe to allow your visitors a way to submit some kind of content of their own, then here’s a way you can create a new post form and display it on a custom page template.

In order to write a new post in WordPress you have to do a number of steps just to get started. First you must login to get to the dashboard, then go to posts, and then add new post.

That’s a total of 3 page refreshes with the need to type your name and password as well, and that’s just to get to the post write page.

If you have members of your site that join so they can submit some kind of content or another, it can be even better for them as well to not have to go through all the steps it takes in submitting a new post. Plus this can be used for making a new post form for custom post types, too.

Whilst you’re playing with custom post types, you might like to get some awesome styling set down using WordPress’ blog_class function.

This custom post form is something I developed after trying all the form plugins I could find, including the more well known Gravity Forms plugins which both are quite capable of doing this but are more than I needed.

I’ve even hacked, dissected, and attacked the Prologue and P2 themes since they are Twitter-style themes that have a post form right on the main page. I mean I ripped them both apart, and slaughtered the code in them to death, and failed.

Prologue couldn’t do what I wanted, and the P2 theme code is so intertwined within itself it was just too much of a pain to undo the knot of code it consists of.

1. The Form

First we will set up the basic form which you can use to enter in the information to submit new posts.

<!-- New Post Form -->

<div id="postbox">

<form id="new_post" name="new_post" method="post" action="">

<p><label for="title">Title</label><br />

<input type="text" id="title" value="" tabindex="1" size="20" name="title" />

</p>

<p><label for="description">Description</label><br />

<textarea id="description" tabindex="3" name="description" cols="50" rows="6"></textarea>

</p>

<p><?php wp_dropdown_categories( 'show_option_none=Category&tab_index=4&taxonomy=category' ); ?></p>

<p><label for="post_tags">Tags</label>

<input type="text" value="" tabindex="5" size="16" name="post_tags" id="post_tags" /></p>

<p align="right"><input type="submit" value="Publish" tabindex="6" id="submit" name="submit" /></p>

<input type="hidden" name="post_type" id="post_type" value="post" />

<input type="hidden" name="action" value="post" />

<?php wp_nonce_field( 'new-post' ); ?>

</form>

</div>

<!--// New Post Form -->

There’s nothing special with this form really. The only thing is the wp_dropdown_categories() function, which creates the list of categories you can select from. You can learn more about this function here. Everything else you enter into the form will automatically create a new entry, including tags. Make sure no matter what you do, always include the wp_nonce_field(), for security reasons.

2. The PHP for Processing the Form

Here is where the fun part begins. This is the PHP which you need to process and submit the form information.

<?
if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] )) {

	// Do some minor form validation to make sure there is content
	if (isset ($_POST['title'])) {
		$title =  $_POST['title'];
	} else {
		echo 'Please enter a title';
	}
	if (isset ($_POST['description'])) {
		$description = $_POST['description'];
	} else {
		echo 'Please enter the content';
	}
	$tags = $_POST['post_tags'];

	// Add the content of the form to $post as an array
	$post = array(
		'post_title'	=> $title,
		'post_content'	=> $description,
		'post_category'	=> $_POST['cat'],  // Usable for custom taxonomies too
		'tags_input'	=> $tags,
		'post_status'	=> 'publish',			// Choose: publish, preview, future, etc.
		'post_type'	=> $_POST['post_type']  // Use a custom post type if you want to
	);
	wp_insert_post($post);  // Pass  the value of $post to WordPress the insert function
							// http://codex.wordpress.org/Function_Reference/wp_insert_post
	wp_redirect( home_url() );
} // end IF

// Do the wp_insert_post action to insert it
do_action('wp_insert_post', 'wp_insert_post'); 

?>

Let’s go over this.

The first line checks if a post has been submitted, and if the action is not empty. You could do this check a number of ways, this is just how I’ve done it:

if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] )) {

The second part is a basic form validation that checks to see if the title and description fields are set, and if so set the values to the variables $title and $description. You may want to check that each of the fields are set this way but I am just showing as an example.

Then, I set up a variable called $post, which is an array of values from the form fields.

  • post_title = $title like we set above using the validation
  • post_content = $description as we set
  • post_category = the category that was selected
  • tags_input = the tags
  • post_status = publish, future or draft. Whatever you want to set it to
  • post_type = post, page, or if you have set up a custom post type you can use that instead

To insert the new post information you can use the function wp_insert_post() and passing the $post variable to it. This is all of course, only if the form has been submitted which is why we put all this within the ‘if’ statement.

Update: I’ve added the function wp_redirect() after the wp_insert_post() function, to fix the redirect to a 404 page. You can change the location by passing the function an argument. For example: wp_redirect( ‘/some-page/’) or wp_redirect( home_url() ).

Close the IF statement and then add the action. The line do_action(‘wp_insert_post’, ‘wp_insert_post’); will add the wp_insert_post hook, with the wp_insert_post from the if statement as the callback, thereby adding the $post variable with all it’s information to the function. Without this line the post will not be submitted and your form will be useless.

I will leave the CSS up to you since I am not here to make your form look pretty, just work. Besides, everyone styles things differently anyways.

You can embed this code in a custom page template, say for example: page-submit.php. Copy the code from page.php and paste it in your custom template. You can create custom pate templates using page-slug.php or page-id.php. I find making custom templates this way 100 times better than using the old way, which involves assigning the page a specific template in the page attributes.

Make sure that you create a new page in the WordPress dashboard, and that your page slug or page id match the name of your template file (ie: page-submit.php – page slug = submit). This new page you create will automatically use the custom template you make, so there is no need to do anything else. You can enter content into the page if you choose to of course, but as long as the custom template includes the new post form, either above or below the_content() function you are good to go.

Download this code here

If you have any questions about this, or can’t get it to work let me know in the comments.

This is a guest post by Jared Williams of New2WP.com

Found this helpful? You'll find us helpful!

WPShout is published by a full-service WordPress-loving constultancy, Press Up. Get in touch with us about your project or business idea, we're knowledgable and friendly.

About the author

Jared is from Boston working as a web and graphic designer. Developer and author of New2WP.com and the design blog Tweeaks.com, and several other Wordpress powered sites.

123 Comments

  • SImon

    Is there an option to submit custom post types from the frontend?
    Would be very nice ;)

  • Does this check if the user is registered and logged in so as to be compatible with the WP roles and capabilities?

    Does this have any ability to avoid spam?

  • Gravity forms also provides this functionality: http://www.gravityforms.com/category/features/

    • Benji

      Unfortunately gravity forms doesn’t enable me to allow my users to import web elements (i.e. a FB Album), or to record anything (webcam). Would be great otherwise.

  • Thats awesome. Been looking for a slimmed down version of this.

    Is this however 100% secure?

    Fox

  • @Simon Yes you can use this for custom post types. The form has a hidden field, <input type=”hidden” name=”post_type” id=”post_type” value=”post” /> with the value ‘post’. Simply change this to whatever your custom post type is and the $post array will insert the data into that post type.

    @Sooraj If you want to check if a user is logged in before showing this form to just anyone, you can do something like this:
    if( !is_user_logged_in() ) {
    // not logged in, redirect to login form.
    } else {
    // is logged in, show form here.
    }

    This form does not include any anti-spam features (eg: captcha). If you made it visible to only logged in users, you wouldn’t have to worry about spam as much, unless you had spam bot accounts that were registered, which would be a different thing altogether. Easy to remove those too.

    @Devin Yes, I mentioned in the post that both TDO and Gravity Forms have the ability to do this same thing. I found them both to be more than I needed however. This doesn’t require a plugin. I always try to reduce the need for more plugins when adding new features to my sites.

    @Foxinni Yes it is secure, as long as you make sure to use the wp_nonce_field( ‘new-post’ ); which I have included as part of the form.

  • thank you, Jared, that’s awesome!

  • No problem :)

    If you would like to see a live/working example of this as a custom post type form that requires you to be logged in, you can check it out on the site I originally developed it for.

    http://tweakurpages.com

    It’s my test site/theme, and since it requires you to be logged in to access the post form, click the login button on the top right and login with:

    Username: contributor
    Password: contributor

    Once logged in, the menu buttons on the top should change. Click the submit button and try submitting something using the ‘site’ post form, which will submit a new post to the Gallery of the site. The forms on the other tabs don’t work currently so don’t bother with those.

  • Hi Jared,
    That’s certainly a new turn on things. My only concern, which I would like to hear you address, is that when you dig that deep and custom code, especially when you bring outsiders into your Blog, what are the security risks? What precautions can you take to assure that you are not providing a convenient target for your Blog?

    • This is of course no doubt a concern. Security is always a must, which is why I made sure to include the wp_nonce_field() in the form.

      Read more about nonces, and how to use them here http://codex.wordpress.org/WordPress_Nonces.

      As it says in the codex ( http://codex.wordpress.org/Function_Reference/wp_nonce_field ):

      “The nonce field is used to validate that the contents of the form came from the location on the current site and not somewhere else. The nonce does not offer absolute protection, but should protect against most cases. It is very important to use nonce field in forms.”

      Also, if you use this to make a form for logged in users of your only, you should have less concerns about security problems as well.

      Hope this helps ease your concerns about the security.

  • Brill! (I`m working on a scheme to allow readers to comment, registered readers can choose either comment or new post … had this on my horizon … thanks!)

    “bentrem

  • Hey Jared,

    Glad to see you here.

    Really Great Post. Very Useful for multi-author blogs.
    Thanks for sharing this great Post dude.

    keep up the good work.

  • i have checked and double checked everything and when i shit publish it takes my to my site to the Error 404 – Not Found

    dont know why

  • Good stuff! But when I try this with wp3.01, I get a 404 after posting. Any Ideas why? (It works perfectly on 2.9.2 though)

  • Erik Veltman

    I tried the same, I’m leaving the <form action="" blank, supposing that the form posts to itself (which is a permalink to my custom template).
    Everytime I push PUBLISH I get to a not found page error …

    I created a page_idee.php template in my themes folder, I get there if my url is /baseurl/publiceer-idee/, but the form post is not getting there.

    Do you have any idea?

  • Oh sorry, I completely forgot about that. I was supposed to add the hidden input field for the redirect, I remember running into this problem before now too. I haven’t had it happen for a little while now and I believe that may have to do with my use of template_redirect() function for my custom post types I’ve setup.

    I’m not sure if this will be a full proof solution, or even solve anything (it does work for me).
    Try adding this hidden field to the form, and put as the value what to redirect to.

    <input type=”hidden” name=”redirect_to” value=”<?php site_url( ‘/CoolPostType/’ ); ?>” />

    I know there’s another way to do it if this doesn’t work for everyone. I am going to try to figure out a more solid way to redirect too, since this isn’t as ideal.

    • I too am getting the perpetual 404 errors and no success actually posting to WP 3.0.1.

      Has anyone had success getting this to work?

      Also two questions for the group:

      1) Has anyone tried to get this to work with the Multi-Site features of 3.0.1?

      2) Have you had success posting custom post_types?

      I’m wanting users to be able to submit posts JUST of one type and posting them to just the blog that they own…. Any tips/advice are appreciated!

  • Natasha

    Hey there this code is exactly what I have been looking for. Any word on how to get it to work in wordpress 3.0?

    • This does work in 3.0. Are you trying to use it for custom post types? All you have to do is change the value=”post” of the hidden post_type input field in the form to have a value of whatever your post type is.

  • Simon

    Hi,

    i do not get it…
    It always procudes a 404 error?!

    A second qustion ist the possibility of required fields. How can i define them?

  • I figured it out!!!

    I’m sorry for those of you who have been getting 404 or other redirect error message.

    If you add this after the wp_insert_post($post) you can control where the page redirects…

    wp_redirect( $location );

    $location can be whatever, for example:

    wp_redirect( home_url() );
    wp_redirect( ‘/some-page/’ );

    And maybe even (haven’t tested this yet):

    wp_redirect( site_url(‘/?post_id=’ . $post_ID ));

    Look in the codex where wp_redirect() documentation is for more info. Hope this clears up everyone’s problems.

  • To make it more secure and avoid SQL injections I think that you should add to your script the stripslashes() and mysql_real_escape_string() funcions

  • Pretty nice example. Thank you!

    Do you know how to make the same but using custom taxonomies too?

    E.g.
    Custom taxonomy: ‘Book Genre’
    Taxonomy terms: ‘Horror’, ‘Action/Adventure’, ‘Suspense’, ‘Drama’, ‘Romance’

    Showing it as a select dropdown? it doesn’t need to be autogenerated, I just want to know how to store the value with the wp_insert_post() function :)

    Thanks in advance!

  • blizzle

    every form has to redirect after it’s done handling the form

  • I’m using your latest code but still it gives the 404 error.

  • Raghav

    This code breaks in 3.0.1.

  • Corrupted

    I’m so noob at this, it pisses me off…

    Anyway, as I stated I’m very amateur at all the php sql stuff. Maybe you think my concerns are so lame you wouldn’t answer but I understand.

    Where do I have to paste the code of the form? and where do I have to paste the php code? and what do I have to write inside the action brackets: action=”WTF”

    So far I’ve spent hours on this and the only logical thing to do (for me) was:

    Try1

    Paste the form code in a new Page (created in the wordpress dashboard), this would create a page with the form code.
    Then create a php file called post.php (or whatever.php) whit the pho code you provide.
    And at last put in between the action brackets in the form the php archive I’ve just created: action=”post.php”

    The only thing I got with this was a fatal error of the php file regarding the wp_insert_post function. Something I also couldn’t understand.

    The next logical thing (to me) to do since I read all the stuff about the page-(slug).php files was try it.

    Try 2

    Since I read all the page-slug.php files and I saw you uploaded a txt file (New_Post_Forn_by-Jared_New2WP.txt) I thought the code shuld be together in a page-slug.php file so I proceeded to create a page called Submit un the WordPress dashboard and the corresponding page-submit.php file in the theme’s directory with all the code form the txt file pasted as it was, without any edit at all.

    It didn’t work… xD

    I’m now here before you begging for some help.

    Thanks so much for even read all my problem!

  • How would I modify the code above if I wanted to also submit custom fields with a front end form?

    For instance I have a custom field titled event_Cost that I want a user to be able to submit with the rest of the post.

    thanks.

  • Like Joe, I too am still getting a 404, even with the latest code. Using WP 3.0.1.

  • Great tutorial. I have a question regarding author. Do I need to define the current user if a author is logged in? or is this done automatically.

    @simon – The first part of the PHP script has the validation stuff. Using Isset to check if the field is empty. Returning a error message if empty.

  • Colin

    having trouble getting this working locally with MAMP, i just get my “no post found” error from my loop on submit :/

  • Bohdan Hdal

    wp_redirect dont helped for me. I have 404 error in wordpress 3.0.1

  • Bohdan Hdal

    Please delete other my wrong posts.

    I fixed 404 error in wp 3.0.1

    for return to the same page:
    delete:

    <input type="hidden" name="post_type" id="post_type" value="post" />

    and insert:
    <?php global $post; ?>
    <input type="hidden" name="page" id="page" value="< ? php echo $post->ID; ? >"/>

  • Bohdan Hdal

    Please delete other my wrong posts.

    I fixed 404 error in wp 3.0.1

    for return to the same page:
    delete:

    <input type="hidden" name="post_type" id="post_type" value="post" />

    and insert:
    <?php global $post; ?>
    <input type="hidden" name="page" id="page" value="< ? php echo $post->ID; ? >"/>

  • I have same problem like Joe. AND if i leave fields empty i also get 404 error :S

  • Great code, thanx for that.

    I also got the 404 error but managed to fixed it by removing the hidden “post_type” field. Apparently this field also conflicts somewhere.

    You can set the post type in the server-side validation, this might also add some extra security to the form.

  • I found that strange 404s can be caused by naming conflicts with WP, such as form fields named “name”. Try naming all your form fields with unique identifiers!

    E

  • Hi–not sure if my previous comment got through our not so I’m reposting…

    This is great and just what I need for a project I’m working on currently. However, I too am getting the 404 error and nothing is posting to the database.

    I’m using WP 3.0.1 on a local install on my MacBookPro. Using the latest version of the code example.

    Anyone successful in getting this to work properly?

    Thanks!

  • same here, still 404 error when I hit submit.
    the php file name is: page-submit.php and the slug is submit.
    I access the form from this url: http://www2.salone-studente.it/wordpress/submit/

    any help

  • I have same problem: 404 error with latest code. Any clue?

  • Thanks for the article!

    For most posts I use custom fields for images (portfolio images).

    Any thought on how to add a file upload field that would add it to a custom field key.

    Maybe, add_post_meta()?

    Thx!

  • Yeah, same here, 404 upon submit. After a bit of googling I found this site and changed the variable names in the form (and the related values in the php part), and suddenly it worked. Not sure which variable is causing the problem, but at least one seems to interfere with a standard WP post variable, then apparently causing the 404.

    http://www.cabeeb.com/2009/09/posting-a-form-to-a-wordpress-page/

  • I’m still struggling with it, but I think I found the spot.
    I’m using it on a custom post type and if I keep the declaretion of the custom post type in the functions.php file it gives me a 404 error. If I comment out all the declaretions the post are saved correctly. strangely I did not change the post type hidden input in the form and it saves it like a custom post type….
    any thoughts?

  • I was also getting a 404, I ended up taking this line out of the form:


    <input type="hidden" name="post_type" id="post_type" value="post" />

    which means you will have to set your action php


    $arr_Cats = array(); //set all categories here

    // Add the content of the form to $post as an array
    $post = array(
    'post_title' => $title,
    'post_content' => $description,
    'post_category' => $arr_Cats, // Usable for custom taxonomies too
    'tags_input' => $tags,
    'post_status' => 'publish' // Choose: publish, preview, future, etc.
    );
    wp_insert_post($post);

    You will notice that there is no longer a post_type in the $post array, so it this will automatically insert as a post instead of a page. Also, the categories should be inserted as an array otherwise there will be a warning output on the page.

  • I’m using the form and is going good, but it creates a post in a post, and not for custom post types.

    I put this line, and it doesn’t go…

    ‘post_type’ => $_POST['hotel']

  • I think the solution to the 404 redirect error issue, has to do with using the $_POST superglobal to set the post_type in the array.

    Try doing this instead in the IF statement.

    if( ‘POST’ == $_SERVER['REQUEST_METHOD'] && $_POST['posttype_form_field'] == ‘movies’ ) {

    Then in your IF ELSE, where you create the $post array, just set the directly.
    ‘post_type’ => ‘movies’,

    See if that makes a difference. This is how I have my custom post type class/post form set up and it does work just find.

  • Wow, thanks for this post, exactly what I was looking for! However, like some others, I am getting the 404.

    I tried simply removing the hidden input of but that didn’t help.

    Unfortunately, I don’t really understand the other suggestion by Paul above.

    I’m at a loss for the moment, but I hope someone here may be able to offer a clearer explanation to a non-code wrangler type like myself as to what I may need to do to get this working.

    Any takers? I’d be happy to provide my page template code and/or FTP access.

  • I’ve been experimenting and am getting form submission and post creation, but I am getting some errors. I think the $arr_Cats = array(); will solve things, but I am looking for an explanation of what I should be entering in this array.

    To get the submission to work, I removed the hidden input as suggested by Paul and others above. This is what I removed

    Just removing this allowed me to get past the 404 and my form to be submitted as a post, although upon hitting publish the screen showed some errors.

    Warning: array_filter() [function.array-filter]: The first argument should be an array in /home/ada/public_html/example.com/wp-includes/post.php on line 2187

    Warning: Cannot modify header information - headers already sent by (output started at /home/ada/public_html/example.com/wp-content/themes/twentyten/header.php:12) in /home/mybody/public_html/example.com/wp-includes/pluggable.php on line 890

    So, back up to Paul’s comment above. He said:

    "which means you will have to set your action php"

    $arr_Cats = array(); //set all categories here

    This is where I get a bit lost. Do I need to enter all my existing categories in this array? If so, how?

    For now I just added $arr_Cats = array(); above the “Add the content to the form” part and then changed the 'post_category' portion to Paul’s specs and my form submits and the Warning: array_filter() [function.array-filter]: warning is gone. But the category I choose upon submission isn’t working. Every post goes to Uncategorized.

    The “Headers already sent” error is still there also.

    I know that my lack of understanding of PHP is at play here. Can anyone help me straighten this out?

    This is my code as I have it now. Forms are submitted as posts, without the category selection working, and page refreshes to show “Headers already sent” error.

    Full page template here:
    http://pastebin.com/i2cvgGDG

    • I found after posting this that the category variable should be set as an array yes.

      I rewrote it with some needed changes, and some that may not be right.

      http://pastebin.com/KniQsKms

      I commented it alot
      I’m not sure if it works, I haven’t tested it. But I will be writing an update to this tutorial on http://new2wp.com which I will show how to create the version of this which is live and working just fine and used on http://2010.wphonors.com and available to over 600 users.

    • To solve the problem :
      Cannot modify header information - headers already sent by (output started at /Applications/MAMP/htdocs/codesphp/wp-content/themes/codesphp/header.php:16) in /Applications/MAMP/htdocs/codesphp/wp-includes/pluggable.php on line 890
      You have 2 solutions :
      1- Comment line 890 header("Location: $location", true, $status);
      2- Add this code in the first line on wp-includes/pluggable.php:

      • asafche

        The “Cannot modify header information” is caused by the spaces in this PHP call “<input type="hidden" name="page" id="page" value="ID; ? >”/>”

        between the “”.

        the problem that i can’t solve is this:
        “Warning: array_filter() [function.array-filter]: The first argument should be an array in /home/freeall2/public_html/trial/wp-includes/post.php on line 2187″

        can someone point me to the cause?
        thanks.

  • Hello. Is it possible to add the capability to upload an image to this script? I’m new to the WordPress/Buddypress.

    Thanks,
    Erich

  • Okay, I got the image upload working, but I’m not able to attach the upload to the post. How do I get the ID of the post being created?


    if ($_FILES) {
    foreach ($_FILES as $file => $array) {
    $newupload = insert_attachment($file,$post_ID);
    // $newupload returns the attachment id of the file that
    // was just uploaded. Do whatever you want with that now.
    }
    }

    Where $post_ID is is where the post id is supposed to go and that should attached the image to the post being created.

    • Yes it is possible. You need to do something like:

      update_post_meta( $post_id, ‘_thumbnail_id’, $thumbnail_id );

      Hope this helps out some.

  • Because this tutorial hasn’t worked for so many of you, I plan to write a follow-up post for it on http://new2wp.com.

    I will show how to create it with a Php Class for custom post types, and how to make this frontend post form submit either via Ajax so the page doesn’t refresh at all, or how to redirect to the post itself upon submitting it.

    If you want to see the working example of what I mean, go register on http://2010.wphonors.com and once logged in, click the submit button in top right of site, which you will see 4 tabs for custom post type post forms. They all work.

    I will show how to create one of those forms. I’ll update this post once I write the tut. Sorry for the 404 problems.

  • Looks good – actually I am searching for weeks for a good answer – question script that works with WordPress – I’ve seen a good solution that allows user “to post a page” and this is what your code does. As far as I’ve seen you need to be logged in to ‘post a page’ (I checked your demo sites) – ok, I’ll try this out seems to the solution for very simple WP Q&A or user generated pages ;)

    thx Heiko

  • I cannot figure out how to upload an image into the post, please help

  • I find solution, everything works, categories, and no errors in wp 3+, here CODE^


    if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] )) {

    $post = array(
    'post_title' => $_POST['title'],
    'post_content' => $_POST['description'],
    'post_category' => array($_POST['cat']), // Usable for custom taxonomies too
    'tags_input' => $_POST['post_tags'],
    'post_status' => 'publish', // Choose: publish, preview, future, etc.
    'post_type' => 'post' // Use a custom post type if you want to
    );

    if ( !$post['post_title'] )
    $error = __('?? ?? ?????? ??????.', 'frontendprofile');
    elseif (!$post['post_content'])
    $error = __('??????? ?????????? ?????? ???? ???????', 'frontendprofile');
    else{ $display = "display:none;";

    $error =__('??????? ?? ??? ??????', 'frontendprofile');

    wp_insert_post($post);

    $post_title = $post['post_title'];
    $page = get_post_by_title($post_title);
    $permalink = get_permalink($page->ID);
    $link = ''.$post_title.'';
    }

    } // end IF
    // Do the wp_insert_post action to insert it
    do_action('wp_insert_post', 'wp_insert_post');

    <form id="new_post" name="new_post" method="post" style="" action="">
    ??????

    ??????? ???? ???????

    ?????????

    ???? (????? ???????)

    <input type="hidden" name="page" id="page" value="ID; ?>"/>

  • Hi,I have some problem about it.It worked when I used it to preview. But there some problem when I publish it. It’s that something wrong about my theme

    • You need to set the category variable as an array like.

      $cat = array($_POST['cat']

      then you use $cat in the $post array instead of the $_POST['cat']

      Or you could just change it to array($_POST['cat'] in the $post array.

  • hi jared
    you code works fine , until i encountered some problems while adding custom taxonomy instead of post category.
    http://pastie.org/1308157 .this is my code yout can see i have mentioned a custom taxonomy for the drop down list. but it is not categorized when given and also the tagging works when only one is being given ,when a bunch of tags are given it doesn’t accepts it.
    i don’t know how to validate my forms it would be usefull if you help with it
    thank you

  • I need more help. I put it on its own page but the php didn’t work. I need some more help.

    I want something where people can pick the title, the category, and it will generate them a special author code.

    Can you help?

  • Jeremy

    This is very exciting because you have described exactly what I need to accomplish. However I am missing something in the implementation.

    If I copy and paste the code into my page template, the form will appear but submitting form info does nothing except refresh the page. It’s not hitting the form validations either if I leave title blank, for instance.

    Is the PHP supposed to be separated out into a separate file and used as the form action? Could someone provide a link to a working example? There’s something I’m missing. But it’s so close!

    Thank you for posting this.

  • peter gibbons

    @jeremy.

    you need to change the action of the form! its blank in the script.

  • To add a term for a custom taxonomy, you need to use wp_set_post_terms.

    wp_set_post_terms( $post_ID, $tags, $taxonomy, $append );

  • Ciocanel Valentin

    This seems so complicated! Couldn’t you explain for those of us that aren’t very familiar with scripting? I would like to know what changes do I have to make in the code and where to paste it; Of course I’d want all of this: “make adding new posts without having to log into the WordPress dashboard, or maybe to allow your visitors a way to submit some kind of content of their own”

  • @Peter (or Jared): change the action into what?

    • dreeh

      Did you ever get an answer to this?

      • the action is the location of the php script. If you saved the php script into a new file called frontpost.php and placed it in the root of you wp installation, then action=”/frontpost.php”

        However, I’m getting: Call to undefined function wp_insert_post() when the form calls the php script…

  • piojos

    every time i refresh i get a new post with the last things i wrote what can i do to just publish it once,

    and if i dont write the content, i dont get any notice

    what can i do?

    btw, what should my action be?

  • This is very exciting because you have described exactly what I need to accomplish. However I am missing something in the implementation.

  • Philip

    yes can someone explain us how to make this code work?

    thanks a lot!!!

  • I will be publishing a follow-up post tutorial to this one on Monday (in 2 days) that I wrote based on the code I developed and am actively using on http://2010.WPHonors.com that enables users to submit new posts to 4 different custom post types from the front end of the site.

    The tutorial uses the same exact code I am using on the site, and I have tested it multiple times and am confident that it will work for everyone. Of course now that I said that it….

    If you’re still trying to get this code to work, come check out http://new2wp.com on Monday for the follow-up post, and learn how to make this work.

  • Philip

    thanks Jared,

    can’t wait to read about your solution!

    thanks a lot,
    Philip

  • I manage somehow with this form to publish it to my CPT but failed to assigned the post to each category.

  • Hy!

    Good post.

    After publishing my site I get a 404 page. Something screwed up? I copied the code in the same way as you are here.
    Sorry for the bad english.

  • hi whether it is possible to include the custom field option in this form were user can enter the custom values from the frontend

    Thanks and waiting for your response…

  • Vasya

    Nothing but 404 page…

  • I’ve got the form working fine, the path to the script as the action but on Submit, I end up on the (blank) script page. What’s wrong?

  • Eric Hamby

    Not working at all, either get errors or the category function wont work.

    image upload?
    custom fields?

  • Alfredo

    you can also add the image upload?

    thanks.

  • Hi, great tip, but like all other article on submit in front-end, how to allow user or guset to attach image and post in directly in article ?

  • It DOESN’T work…

    Just try and copy all that code in a page template and hit Post.

    It returns a 404 and does not insert anything in the database.

    After removing the hidden inputs and the check for ‘action’ not being empty, it returned a “cannot modify headers”…

    I’m really wondering if anyone really tested it. Just copy/pasting the code won’t work… Am I missing something?

    • Same thing is happening with me…
      did you find any solution for this?
      why are we getting 404 error..

  • Hey guys,

    So I wrote my own.

    I’ve extended it to check the database when a new post is inserted. If the DB already contains an exact same post, you get an error.

    So here it is: http://wordpress.pastebin.com/j1anH8Gj

  • Hi, how do i add attachments like images or video?

  • How can we add custom meta fields to the form?

    Awesome tutorial! Its nice not to use a separate plugin for this.

  • Crazy thing is that I was just reading about this very same thing last night. There’s a post here http://lewayotte.com/2010/09/27/using-wordpress-built-in-media-upload/ about using a front-facing form and WordPress’s media uploader to post from the front end. Then I see you tweet this article last night. You merge these two posts and I think you really got something.

  • I’ve got most of this working, but I hope you can help with one other thing. I want the user to be able to select multiple categories. I thought I achieved this by setting the category dropdwown to only display children of a certain parent. Then I duplicated that drop down to show children of another parent. That way they can select a category from parent A, and another from parent B.

    This didn’t work. If a category is selected it no longer applies that selection. Can you explain how to allow for this sort of multi category drop down selection ability? Thanks!

    • You need to use a single select element and add the attribute to it for multiple. so…
      <select multiple=”multiple”>

      Then you need to make the php variable set as an array. so you would do something like this in the $post array

      ‘category’ => array( $catVariable ),

      That should do it. not 100% sure that’s all you need to do though.

  • Karthik

    Hmm, I also seem to get errors when just copy pasting the code:

    Leaving action as blank I get a page not found error

    Moving the php file to “test.php” in my wordpress root, and then using action = “/test.php” results in a wp_insert_post() undefined function error.

    What could be going on?

    Oliver did you ever solve your problem?

  • it return a 404 because you are sending the form to a post/page location, but if you send it to the actual file it will give you the “wp_insert_post() undefined function error” because the file is outside the WordPress environment.

    what it works for me is something that shouldn’t been made but it works.

    2 choices:

    1 add the php in the 404.php file of your template, so when you get the 404 it will catch the POST method and do the action.

    set the redirect to your home page or wherever you want to and it wouldn’t be noticed.

    2. add the php in your main header, that way it will grab the POST anywhere.

  • upload pictures and add code?

    • help please

    • Michael

      Everything works great except that I cannot edit/trash new custom posts created from this form. Would anybody have any clue as to what could be causing that?

      I’ve searched online but had no luck with a solution. My custom post type has ‘capability_type’ => ‘post’, and when I add new posts from the admin page the problem doesn’t arise. I would be grateful for any suggestions!

  • David

    I have this working pretty well… Only question I have is..

    I want each “poster” to be able to add their name (author) to the post they submit.

    Adding ‘post_author’ into the new_post array doesn’t seem to work.

    Is there a way to get that working?

  • error 404… for submit post.

  • i do not understand.Is there any benefit from this? Can you please clarify benefits of this..

  • Great tutorial :) Thanks for sharing :)

  • Wow! the first script (and so short) that works! thanks a lot man

  • I managed to get this working but I also need to upload a file the post. Anyone found a solution for this?

  • Hi! Great code thx. But i need just a little help. I have taxonomy name random.

    and when im creating post by this form it doesnt take taxonomy (like i didnt choose)

    Here is my code

    $post = array(
    'post_title' => $title,
    'post_content' => $description,
    'post_category' => $_POST['cat'], // Usable for custom taxonomies too
    and here is place for my taxonomy but i dont know how
    'post_status' => 'publish', // Choose: publish, preview, future, etc.
    'post_type' => $_POST['post_type'] // Use a custom post type if you want to
    );

    pls help thx

  • Thanks for setting me off on the way with this code Jared. Still encountering some errors on the way but have a solid foundation thanks to you.

    Cheers,
    Matt

  • i can now display my custom taxonomies, but i have a problem submitting it. I’m always getting page not found after clicking the submit button. It only happens if i activate my custom taxonomies, but if I get rid of it, it works fine. Can you help me with this?..thanls

  • i found a solution for the custom taxonomies, and it works fine!

  • Devil

    Rhev you’ve found a solution? Smart-ass..!

  • Hi. Thanks for this. I added all the code did everything you said but when I click submit, it reloads the page and displays the default message in my template “The content you’re looking for isn’t here”. And I also can’t find the post in the back end.

    Thank you in advance.

  • Costin

    Hi. Thank you for your interesting post. I had the same problem like most people but I’ve found a solution. So, if anyone is still interested in this, you should change the name of the fileds “post”, “title” etc with something else (Eg. xpost, xtitle) and there will be no more 404s :D.
    Best Wishes!

  • Hi, Thanks for the code.

    I am trying to use this in P2-Child theme. But because of the line
    do_action(‘wp_insert_post’, ‘wp_insert_post’);
    I am getting the warning on my page… it says

    Warning: Missing argument 2 for P2_Terms_In_Comments::update_post() in C:\wamp\www\chutkule\wp-content\themes\p2\inc\terms-in-comments.php on line 45

    Warning: array_merge() [function.array-merge]: Argument #1 is not an array in C:\wamp\www\chutkule\wp-content\themes\p2\inc\terms-in-comments.php on line 69

    Can you please help me, why this is happening when i am calling this do_action method?

  • Do you know how I can specify a post-format when using this function?

    In wp_insert_post I don’t see format as an option you can specify, and I’m not sure where I would use set_post_format in your function.

  • Tanel

    Excellent lightweight tutorial, thanks!

    Although, it could use some updating regarding post categories and sanitation: http://codex.wordpress.org/Function_Reference/wp_insert_post

  • Do you know how I can add anti-spam in form by front end code?

  • Can your code be modified to include an expiration time for the post. I’m trying to use an expire plugin but it doesn’t work with any front end posting solutions I can find.

    Thank you in advance for any assistance.

  • Hi great code thanks,
    but post_category no exists,
    so how i can use wp_set_post_terms() for a post’s categories.?

  • Hi and thanks for the article. I am attempting to get this example working but have an issue which I am hoping you can assist me with.

    I used all your suggestions. I copied page.php to page-submit.php and add the submit slugged page using the dashboard. I modified the page.submit.php page to hold the code referenced here. i left the header and footer and sidebars calls in there too. The page shows fine but when I publish the post from the frontend, I get a page not found error. I am redirecting as you have shown to the home_url()…. wp_redirect( home_url() );

    I am not sure what the issue is or maybe I am missing something. i appreciate any insight you might offer here. Thanks!

    Jeff