Dynamically set the post type when creating a post

Created by Phil Kurth, Modified on Mon, 11 Aug at 12:54 PM by Phil Kurth

<?php
add_filter( 'af/form/editing/post_data', function ( $post_data, $form, $args ) {

  // Check if this is the correct form. If not, return the post data as is.
  if ( $form['key'] !== '{YOUR_FORM_KEY}' ) {
    return $post_data;
  }

  // Get the selected post type from the submitted form field
  // Replace 'post_type_selector' with your field name or field key
  $selected_post_type = af_get_field( 'post_type_selector' );

  // If the selected post type exists, set it for the post being created
  if ( $selected_post_type && post_type_exists( $selected_post_type ) ) {
    $post_data['post_type'] = sanitize_key( $selected_post_type );
  }

  return $post_data;

}, 10, 3 );

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons

Feedback sent

We appreciate your effort and will try to fix the article