Support » Developing with WordPress » Checking user capabilities documentation bug

  • According to Checking User Capabilities documentation, the way you check if user_can edit others’ posts is not working –

    if (current_user_can('edit_others_posts')) {
    /**
    * add the delete link to the end of the post content
    */
    add_filter('the_content', 'wporg_generate_delete_link');
     
    /**
    * register our request handler with the init hook
    */
    add_action('init', 'wporg_delete_post');
    }

    It returns Fatal error: Uncaught Error: Call to undefined function wp_get_current_user() in /app/public/wp-includes/capabilities.php:652, And it happens because /wp-includes/pluggable doesn’t get loaded until after the plugins are loaded, So I guess that the right way to do this is to wrap this conditions in a function and hook this action into ‘init’, like this –

    /**
    * add the delete link to the end of the post content
    */
    add_action('init','check_user');
    
    function check_user() {
    if (current_user_can('edit_others_posts')) {
    add_filter('the_content', 'wporg_generate_delete_link');
    
    /**
    * register our request handler with the init hook
    */
    add_action('init', 'wporg_delete_post');
    }
    }

    Let me know if this is the right approach in this case.

    • This topic was modified 1 week, 2 days ago by rikavon.

    The page I need help with: [log in to see the link]

Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    Thanks for reporting the flaw in the example code. I think the example may have come from a file that is loaded late enough for capability checks to work. I’m not excusing it as an example, it doesn’t illustrate best practice.

    What you propose is good practice. Virtually all custom code in WP should be done within filter and action callbacks. The exceptions being the actual add_action() and add_filter() calls of course. The only other exception that comes to mind is template code.

Viewing 1 replies (of 1 total)
  • You must be logged in to reply to this topic.