0
votes

I created a custom post type and also custom taxonomy for it, lets call it cpt-category for simplicity. I have 3 cpt-categories for this cpt.

Now, I have some custom user roles in dashboard - but I don't need to, I can just make custom capabilities for Subscriber role with User Role Editor.

But what I need is to make sure that Subscribers can only create new cpt's in one specific cpt-category out of three. So that the cpt-category would be set automatically if Subscriber creates a new cpt.

On the other hand, Admins should be able to choose from all three cpt-categories.

Is there a wp function for this?

Thank you in advance :)

1

1 Answers

1
votes

The subscriber role, by default, cannot edit or create posts. That said, there's no way to limit the categories that someone with the edit_posts capability has access to.

The easiest way to solve this issue would be to create a form in your front-end, that sends back to admin-post.php using the admin_post hook (for logged in users), and then doing your logic within the function for that hook.

Something very basic may look like this:

function create_cpt_post_subscriber() {
    if (!current_user_can('edit_post')) {
        return false;
    }

    /* do stuff */
}
add_action('admin_post_action_name', 'create_cpt_post_subscriber');

You would then use wp_insert_post within that function to create the new post using the $_POST parameters sent to admin_post. Within that hook, you have full access to $_POST as well.

Using AJAX will prevent your Subscribers from getting sent to the 'admin-post.php' page directly, so I'd advise using AJAX to submit the form.

Using wp_insert_post, you'd be able to program in the exact category ID you want them to use. If that category ID changed, though, you'd have to update it in the code as well, unless you used get_term to retrieve it by slug (advisable).

You can learn more about wp_insert_post in the WordPress Codex and there's a tutorial for forms using admin_post hooks on SitePoint.