Support

Account

Home Forums Front-end Issues Create new catorgory

Solved

Create new catorgory

  • Hello ,

    I am curently using acf_form for various forms around the website i am curently working. Is it possible to create a new category for posts using acf form?

  • Yes, it is possible to create a new category for posts using an Advanced Custom Fields (ACF) form.

    You will need to use the wp_insert_category function to insert the new category into the database.

    You can also use the wp_set_object_terms function to assign the new category to the post when the post is created or updated.

    It’s also possible to use a plugin such as Gravity Forms or Contact Form 7 that allow you to create forms and use the acf hooks to handle the form submission.

  • Thanks @johnblogger . I tried using wp_insert_category but failed , instead i solved the problem using wp_insert_terms. Here is the code:

    add_action('acf/pre_save_post', 'my_save_post');
    
    function my_save_post($post_id)
    {
    
    	if (isset($_POST['acf']['field_63be99db578f3'])) {
    
    		$cat_ID = get_cat_ID(sanitize_title_for_query($_POST['acf']['field_63be99db578f3']));
    
    		// Check if category exists
    		if ($cat_ID == 0) {
    
    			$cat_name = sanitize_text_field($_POST['acf']['field_63be99db578f3']);
    			$cat_slug = sanitize_title_with_dashes($cat_name);
    
    			wp_insert_term($cat_name, 'category', array('slug' => $cat_slug));
    		} else {
    			echo 'That category already exists';
    		}
    	}
    }
Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.