Function Friday #19: publish user content to custom post types with Gravity Forms

Function Friday #19

Every Friday, I’m sharing code snippets that I use to customize WordPress. Feedback/suggestions are always welcome! For more information, check out the first post in the series.


Gravity Forms is a super-powerful form builder plugin that I’ve used for all kinds of client projects. Recently I had to figure out how to get their Post Fields to send to a custom post type, instead of the default Posts. These types of fields let you build a form on the front end of your site, where anyone can submit content for publishing (i.e. they don’t need a WordPress login at all).

On the Gather North website, once an attendee has registered, the fields they filled out as part of the registration process automatically publish on the Who’s Going page. I’d already created a custom post type called Attendees, but it wasn’t obvious how to get the Post Fields to use that post type without having to add an extra plugin.

Although it’s a little buried in their documentation, it just takes one function to override the post type!

The code

// Send Register fields to custom post type
function drollic_change_post_type( $post_data, $form, $entry ) {
    if ( $form['id'] != 1 ) { // Form ID 1: Registration form
        return $post_data;
    }
    $post_data['post_type'] = 'attendee';
    return $post_data;
}
add_filter( 'gform_post_data', 'drollic_change_post_type', 10, 3 );

The first part makes sure this only fires on the relevant form. You’ll need to grab the form’s ID from the main Forms page and enter it here (in this case, the ID is 1). If you’re on a different form, this function will simply return the post data unchanged.

If you are on the correct form, this line will change the post_type value in the post_data array from post to attendee:

$post_data['post_type'] = 'attendee';

Replace attendee here with whatever the name of your custom post type is (or with page, if you want the form to create a page instead).

Finally, the code returns the (now altered) post data for submission.

The gform_post_data filter lets you change all kinds of information before the content is created. If you’re using Post Fields functionality on your site, I’d recommend having a read through all of the documentation’s post creation articles to see what else is possible.

As always, remember to name your function with a unique prefix (like I’ve done here with drollic_) to avoid conflicts with WordPress core and plugin functions.

Where does it go?

This function belongs in your theme’s functions file. There’s more information on where different functions can go in the first Function Friday post.

Resources

Leave a Reply

Your email address will not be published.