2

I'm struggling to find the best/quick easy solution to this problem:

I have a plugin that creates companies but stores all of the company info as a user so all information is in the user's profile. I have another plugin (Geo my WP) that only searches for post/pages/cpt's but not users (well they kinda do but based on address and not other user meta data e.g category, which is what i want).

So I thought, if there was a way that when the user creates a profile, a cpt is created and saves some of the data e.g address, maybe category is also stored there as well as post meta data. Seems redundant but then my geolocation plugin works well without heaps of custom changes (if even possible).

Now I'm a bit weary if it is possible to create a cpt automatically and get updated too upon user registration.

Or any other solution?

Btw: I kinda need the Geo my wp as I have other cpt's that I want to use in the search form.

1
  • There's a user_register action and wp_insert_post. If you search around those two things you can probably cobble some code together to get you started.
    – Milo
    Commented Feb 7, 2016 at 0:10

1 Answer 1

3

There is the action hook user_register that is called immediately after a user is added to the database. The user id is passed to the hook as an argument.

You can use wp_insert_post to insert a new post in that action. You just need to get the relevant info from the user and add it to the post. You can add custom fields to the post you create by referencing the post ID that is returned by wp_insert_post.

This is an example of how you would add a custom post type post on user registration - you'll obviously need to change it to fit your needs, but it should give you an idea of what to do.

/*
 * Create new custom post type post on new user registration
 */
add_action( 'user_register', 'wpse_216921_company_cpt', 10, 1 );
function wpse_216921_company_cpt( $user_id )
{
    // Get user info
    $user_info = get_userdata( $user_id );

    // Create a new post
    $user_post = array(
        'post_title'   => $user_info->nickname;
        'post_content' => $user_info->description,
        'post_type'    => 'your_company_custom_post_type', // <- change to your cpt
    );
    // Insert the post into the database
    $post_id = wp_insert_post( $user_post );

    // Add custom company info as custom fields
    add_post_meta( $post_id, 'company_id', $user_info->ID );
    add_post_meta( $post_id, 'company_email', $user_info->user_email );
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.