Hide custom post type field from author?

For a business association website, I’ve built a membership database using a custom post type. Businesses sign up with an online form, which creates a custom post for that business, and when the administrator receives the new member’s dues, she creates a WordPress user for that business and makes that user the author of the post. This is so that the business can update the business’s information when necessary.

The problem is that this scheme allows the business to also update some fields that they really shouldn’t be able to update, such as the expiration date. So, what I want to do is to either hide those fields or make them uneditable when the author edits the posts, but editable when a WP admin edits the post.

Read More

Does anyone know a way to do this?

Related posts

Leave a Reply

1 comment

  1. The easiest way to do that would be to check the capabilities with current_user_can before displaying the field.

    For instance, the administrator role has the capability manage_options which your newly created users won’t have. So you can do something like this:

    <?php
    // wherever your fields are...
    if(current_user_can('manage_options'))
    {
       // display your fields here.
    }
    

    Or if you have an entire meta box on the custom post type’s page you don’t want to show, you can check the capabilities before adding it.

    <?php
    add_action('add_meta_boxes_{YOUR_POST_TYPE}', 'wpse72883_add_box');
    function wpse72883_add_box()
    {
        if(!current_user_can('manage_options'))
            return; // current user isn't an admin, bail
    
        // add the meta box here
    }
    

    It might also be useful to add your own capability to check rather than use a built in one. To give your administrator role the edit_business_details

    <?php
    $role = get_role('administrator');
    if($role)
        $role->add_cap('edit_business_details');
    

    That only needs to happen once — on plugin activation for instance.

    <?php
    // some plugin file.
    register_activation_hook(__FILE__, 'wpse72883_activate');
    function wpse72883_activate()
    {
        $role = get_role('administrator');
        if($role)
            $role->add_cap('edit_business_details');
    }
    

    You can then check for that capability just like manage_options.

    <?php
    // wherever your fields are...
    if(current_user_can('edit_business_details'))
    {
       // display your fields here.
    }