February 3, 2021: Added support for updating custom fields.
Using Gravity Forms to create posts is easy. With a Basic or Pro license you can use Post fields to create new posts on your site. With an Elite license you gain access to the Advanced Post Creation add-on, which can create custom posts, map custom fields, and add uploaded files to the Media Library.
One thing that neither of these methods can do is update existing posts. Post fields and the APC add-on can only create new posts. In this tutorial, we’re going to show you how to pair a snippet with Populate Anything to update existing posts in WordPress. Let’s get started.
Using the Snippet
Step 1 – Add Post Field
Start by adding a Drop Down field to the form called “Post”. Use Populate Anything to populate posts into the Drop Down for the user to select from.
These settings will populate all Posts as choices in the Drop Down. If you want to limit the available Posts to ones that current user wrote, add a filter where Author is Current User.
Step 2 – Add Title Field
Add a Single Line Text field to the form named “Post Title”. Use Populate Anything to populate the Post Title from the selected Post in the Drop Down.
This field populates with the selected post’s title. If the user replaces that title with a new title, the snippet will overwrite that title when the form is submitted.
Step 3 – Add Post Content Field
Next, add a Paragraph field called “Post Content”. This field will also be populated via Populated Anything.
Since WordPress posts contain HTML for formatting, I recommend activating Gravity Forms’ Rich Text Editor in the Advanced tab. Otherwise, the raw HTML will display on population, which can be confusing for the user.
Step 4 – Add Class and Parameters
With all of the fields in place, the next step is to add the following class to your theme’s functions.php.
new GW_Update_Posts( array( 'form_id' => 123, 'post_id' => 1, 'title'. => 2, 'content' => 3, 'meta' => array( 'custom_field' => 4, 'another_custom_field' => 5 ) ) );
This class has four required parameters and one optional parameter.
form_id integer required
The ID of the form which will be used to update posts.
post_id integer required
The ID of the field whose value contains the Post ID.
title string required
The ID of the field whose value contains the new post title.
content string required
The ID of the field whose value contains the new post content.
meta array optional
An array of custom fields whose keys match the custom field’s name and values match the IDs of the field containing the custom field’s value.
With the code in place, the selected post’s title and content will be updated when the form is submitted. Currently the snippet can update the title and content, but we’d love to hear your feedback regarding how you’d like to use it.