0

The function should give the user a feedback, if the data changes of the meta box of a CPT couldn't be saved. In the following code the function returns a WP_Error if the current_user doesn't have sufficient capabilities and so the update_post_meta call won't be executed. That all is working as expected. The meta data will not be changed on saving the post. But no error or other message is shown, instead on top of the post a message appears inside a left green border box "Post updated." That may not happen. That is the wrong message. How can I change this? How should I write the code?

This is the code structure - all the vars inside the function are visible: (important is only the line with "return new \WP_Error ...")

class Foo{

function save_meta() {

         // some code
    ...

         if ( ! current_user_can( $capability, $post_id ) ) {
                    return new \WP_Error( 'capability-error', __( "You have not sufficient rights to save the data", TEXTDOMAIN ) );
            }

        //other code
    ...
        update_post_meta( $post_id, $key, sanitize_text_field( $_REQUEST[ $key ] ) );

    //other code
    ...

    }
}

add_action( 'save_post_{post_type}', [instance of class foo], 'save_meta' );
  • What $capability are you requiring? Is the user in question a super admin? – Pat J Feb 4 at 16:58
  • Yes. I just read in the wordpress documentation. In case the user is a super admin he can do everything even current_user_can retrieves false. Now I know. – Tom Feb 4 at 17:39
  • An additional question: I don't like to throw an WP_Error in case it is a "normal" user but write in the top message box that the post couldn't get saved. How can I process further the return value of the save_meta function to make that happen? – Tom Feb 4 at 17:46
  • This should probably be a separate question, but the short answer is: instead of throwing WP_Error, you can instead add an admin notice using add_action( 'admin_notices', '{function}' );. – Pat J Feb 4 at 21:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.