Using author_can() on custom post types in WordPress

I’m trying to conditionally display some content in a theme using custom roles and capabilities. First, I define a custom role:

add_role('free_vendor', 'Free Vendor Listing', array('read', 'edit_posts', 'delete_posts', 'display_map'));

Read More

This is run directly from functions.php (do I need to add it to an action somewhere?)

Then I use the display_map capability I defined to conditionally display the map:

if (author_can($post, 'display_map')) echo '<li><a href="#map">Map</a></li>';

The only problem is, it doesn’t work! Is there some issue in using author_can() with custom post types? Am I not calling add_role() properly? I can’t really find any decent documentation on using author_can() with anything other than vanilla posts. Is this just not possible?

Related posts

Leave a Reply

3 comments

  1. first about the add_role

    you only need to run this once, so after you paste it in your functions.php and saved
    you can remove it and save again and the role will be there always.

    then about the author_can function, i really never use it so i can tell whats wrong but you can use current_user_can() function like this:

    update

    if ( is_user_logged_in() ) {
         //first you get the curent user info
         get_currentuserinfo();
         //then you can check capabilities like this
         if(current_user_can('display_map')){
          echo '<li><a href="#map">Map</a></li>';
          }
    }
    

    hope this helps

  2. Okay, so here’s what seems to be happening. Adding capabilities directly to the role when it’s created doesn’t seem to work (at least for me). So, instead of this:

    add_role('free_vendor', 'Free Vendor Listing', array('read', 'edit_posts', 'delete_posts', 'display_map'));

    It needs to be something like this:

    $free_vendor_caps = array('read', 'edit_posts', 'delete_posts', 'display_map');
    add_role('free_vendor', 'Free Vendor Listing');
    $free_vendor = get_role('free_vendor');
    foreach ($free_vendor_caps as $cap) {
        $free_vendor->add_cap($cap);
    }
    

    Then I can do what I need to do with author_can():

    <?php if (author_can($post->ID, 'display_map')) : ?>
    <div id="map">
        <h3>Map</h3>
        <?php the_map(); ?>
    </div>
    <?php endif; ?>