metabox - save meta data of custom post type: WP_Error has no effect, even if insufficient capabilities

admin2025-06-03  3

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' );
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748944224a315037.html

最新回复(0)