Skip to content
Advertisement

ACF pro – frontend form and WordPress categories while creating post

I try to build page where user can fill the form (using my custom ACF PRO fields) and save it as a post. Then admin need to check it and publish if everything is OK. So far I have form based on custom post type and ACF fields work good so far. But I need to display checkboxes with native WP categories on the frontend post creator. At this moment user can’t select categories from the list on the frontend. It can be done on the backend after the draft is saved.

How can I display list of checkboxes with my WP post categories ALSO on the frontend while user is filling ACF frontend form?

This is my ACF form array:

acf_form(array(
    'post_id'       => 'new_post',
    'post_title'    => true,
    'submit_value'  => 'Add new',
    'new_post'      => array(
        'post_type'     => 'games',
        'post_status'   => 'draft'),
));

Advertisement

Answer

Here are the steps you can follow so that frontend user can select the category they want. Leave your acf_form function as it is and integrate the below code in functions.php file.

Step 1: Render category checkboxes in frontend for users to select them

function my_acf_render_field( $field ) {
    // Do not show the code in backend acf metabox
    if( is_admin() ) {
        return;
    }
    
    $categories = $terms = get_terms( array(
        'taxonomy' => 'YOUR_TAXONOMY_NAME',
        'hide_empty' => false,
    ) );
    if( !empty( $categories ) && count( $categories ) ) {
        foreach( $categories as $key => $value ) {
            echo '<input type="checkbox" name="category[]" id="cat_'.$value->term_id.'" value="'.$value->term_id.'" />';
            echo '<label for="cat_'.$value->term_id.'">'.$value->name.'</label>';
        }
    }
}
// Replace "your_field_name" with the field name after which you want to show the category checkboxes
add_action('acf/render_field/name=your_field_name', 'my_acf_render_field');

Step 2: Save the categories selected by frontend user in backend new post

function my_save_post( $post_id ) {
    // bail early if not a games post
    if( get_post_type($post_id) !== 'games' ) {
        return; 
    }

    // bail early if editing in admin
    if( is_admin() ) {
        return;
    }
    
    // update the post created by ACF
    wp_update_post(array(
        'ID'            => $post_id,
        'tax_input'     => array(
                    'YOUR_TAXONOMY_NAME' => $_POST['category']
        )
    ));
}
add_action('acf/save_post', 'my_save_post');

That’s it. Now, users can select the categories from frontend as well.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement