Support

Account

Home Forums Front-end Issues Create post + user (linked to eachother) Reply To: Create post + user (linked to eachother)

  • Oke, I am little bit further. I managed to create a post and a user but I am not yet there.

    This is what I use in my template:

    while (have_posts()) {
        the_post();
        
        acf_form(array(
            'post_id'       => 'new_post',
            'submit_value'  => 'Register user',
            'uploader' => 'basic',
            'updated_message' => 'Well done! You made an account and a post.',
            'html_updated_message'  => '<div style="background: rgba(31,205,80,.2); padding: 10px 20px; border-radius: 4px;" class="updated"><p>%s</p></div>',
            'new_post' => array(
                'post_type'     => 'my-cpt',
                'post_status'   => 'publish'
            ),
        ));
    }

    This is what I have now in my functions.php:

    function create_user_via_acf($post_id) {
    	
    	$username = get_field('username',$post_id);
    	$password = get_field('password',$post_id);
    	$email = get_field('email',$post_id);
    	$categories = get_field('categories',$post_id);
    
    	// creating the user
    	$userdata = array (
    		'user_login'    => $username .'-'. generate_random_user_number(),
    		'user_email'    => $email,
    		'user_pass'     => $password,
    		'post_category' => $categories
    	);
    	$user_id = wp_insert_user($userdata);
    	
    	// overwriting the post I created with acf_form()
    	$arg = array(
    		'ID' => $post_id,
    		'post_author' => $user_id,
    		'post_title' => $username .'-'. generate_random_user_number(),
    		'post_content'  => 'content overwritten',
    	);
    	wp_update_post($arg);
    	
    	return $post_id;
    	
    	//wp_delete_post($post_id); //this does not delete the second post
    	
    }
    add_action('acf/save_post', 'create_user_via_acf', 20);

    In the function above, I try to delete the extra post, wich does not work. I do not know why. Further more, I also see there are 2 posts being created, this should be one. Also the title of the post should be the same as the user I am trying to create.

    I created a function wich returns a random integer of 3 numers (generate_random_user_number()) wich I append to the username and post. But it creates one user with e.g. username-123 and 2 posts with post-456 and post-789. Just an example to point out the digits aren’t the same. For different reasons I use the a number wich is called upon 3 times since it generates 3 different numbers.

    It should be post-123 and username-123. Username-123 should automaticly the post_author of post-123. But I just can’t get my head around this.

    I also used add_filter(‘acf/pre_save_post’) but that did not work either.

    Does anybody have any thoughts on this? A lot of thanks in advance.