Edit:

In a plugin I am developing, I need to store payments, IPN and transactions for customers in both frontend and backend. However I am concerned that the admin will use his actions power to delete the transactions or financial data from site which has bad implications.

Question

How can I prevent the admin from deleting payments/financial data in a way that ensures that I’m not trying to restrict admins too much, but also takes customer information and financial data as high priority. I’m not asking what’s the better way for me to do it? But rather asking what’s the better way for WordPress community (as administration, as a customer) as I am trying to avoid future complaints about the way implemented to do this action.

What I currently have

/**
 * Constructor
 */
public function __construct() {

    // Do not allow payments and transactions to be trashed
    add_action( 'wp_trash_post',                            array( $this, 'disable_trash' ) );
    add_action( 'before_delete_post',                       array( $this, 'disable_trash' ) );
}

/**
 * Disable trash
 */
public function disable_trash( $post_id ) {
    global $post_type;

    if ( in_array( $post_type, array( 'payment', 'transaction' ) ) ) {
        wp_die( __( 'You are not allowed to trash payments or transactions.', 'xxx' ) );
    }
}

3 s
3

Here’s another approach using the map_meta_cap filter that’s applied within the map_meta_cap() function within the has_cap() method of the WP_User class (PHP 5.4+):

add_filter( 'map_meta_cap', function ( $caps, $cap, $user_id, $args )
{
    // Nothing to do
    if( 'delete_post' !== $cap || empty( $args[0] ) )
        return $caps;

    // Target the payment and transaction post types
    if( in_array( get_post_type( $args[0] ), [ 'payment', 'transaction' ], true ) )
        $caps[] = 'do_not_allow';       

    return $caps;    
}, 10, 4 );

where we target the delete_post meta capability and the payment and transaction custom post types.

As far as I understand and skimming through the get_post_type_capabilities() function we don’t need the map_meta_cap argument set as true, in the register_post_type settings, to target the delete_post meta capability.

ps:
Here are some good descriptions of the map_meta_cap filter and helpful examples by Justin Tadlock here and Toscho here. Here I found an old example that I had forgot I wrote, that we could also adjust to avoid trash/delete on some given pages and user roles. Here’s an answer by TheDeadMedic that links to an answer by Seamus Leahy regarding register_post_type approach.
Here are some more examples on this site. Hope it helps!

Leave a Reply

Your email address will not be published. Required fields are marked *