在里面Edit Media, 如果我们查看更新附件上的管理通知,它将使用重定向功能来处理这些通知。所以,基本上我们也可以用重定向函数处理这些错误,然后钩子admin_notices
.
下面是我如何处理屏幕错误的方法attachment
编辑媒体。
class my_plugin {
public function __construct( ) {
$this->url_pattern = "/^(([\\w]+:)?\\/\\/)?(([\\d\\w]|%[a-fA-f\\d]{2,2})+(:([\\d\\w]|%[a-fA-f\\d]{2,2})+)?@)?" .
"([\\d\\w][-\\d\\w]{0,253}[\\d\\w]\\.)+[\\w]{2,4}(:[\\d]+)?(\\/([-+_~.\\d\\w]|" .
"%[a-fA-f\\d]{2,2})*)*(\\?(&?([-+_~.\\\\d\\w]|%[a-fA-f\\d]{2,2})=?)*)?(#([-+_~.\\d\\w]" .
"|%[a-fA-f\\d]{2,2})*)?$/";
add_filter("attachment_fields_to_edit", array($this, "videourl_image_attachment_fields_to_edit"), 10, 4);
add_filter("attachment_fields_to_save", array($this, "videourl_image_attachment_fields_to_save"), 20, 2);
/**
* Hook admin_notices
*
*/
add_action( \'admin_notices\', array( $this, \'admin_notices\' ) );
}
/**
* Fire admin_notices function to show message
*
*/
public function admin_notices()
{
global $current_screen;
/**
* Check current screen
*
*/
if ( \'attachment\' == $current_screen->id )
{
if ( isset( $_GET[ \'error\' ] ) && 1 == absint( $_GET[ \'error\' ] ) )
{
/**
* HTML format to show notices
*
*/
printf ( \'<div id="message" class="%1$s notice is-dismissible"><p>%2$s</p><button type="button" class="notice-dismiss"><span class="screen-reader-text">%3$s.</span></button></div>\',
\'error\', //type error or updated
__( \'Your Error Messages.\', \'text-domain\' ), //your error text
__( \'Dismiss this notice\', \'text-domain\' ) //for close button
);
}
/**
* Remove query parameter \'message\' and \'error\'
*
*/
$_SERVER[\'REQUEST_URI\'] = remove_query_arg( array( \'message\', \'error\' ), $_SERVER[\'REQUEST_URI\'] );
}
}
public function videourl_image_attachment_fields_to_edit($form_fields, $post) {
$form_fields["videourl"]["label"] = __("Video URL");
$form_fields["videourl"]["helps"] = "Set a video URL for this image";
$form_fields["videourl"]["input"] = "text";
$form_fields["videourl"]["value"] = get_post_meta($post->ID, "_videourl", true);
return $form_fields;
}
public function videourl_image_attachment_fields_to_save( $post, $attachment ) {
if ( isset( $attachment[\'videourl\'] ) )
{
if ( mb_strlen ( trim($attachment[\'videourl\'] ) ) > 0 && preg_match($this->url_pattern, trim($attachment[\'videourl\'] ) ) ) {
update_post_meta( $post[\'ID\'], \'_videourl\', $attachment[\'videourl\'] );
} elseif( mb_strlen ( trim($attachment[\'videourl\']) ) == 0 ){
delete_post_meta( $post[\'ID\'], \'_videourl\' );
}
/**
* Handle error if empty \'videourl\'
*
*/
if ( empty( $attachment[\'videourl\'] ) )
{
/**
* Build error query for redirection
*
*/
$location = add_query_arg(
array(
\'error\' => 1
),
$post[\'_wp_http_referer\']
);
wp_safe_redirect( $location ); // wp-admin/post.php?post={id}&action=edit&error=1
exit;
}
}
return $post;
}
}
您可以根据需要更改代码。看起来有点棘手,但我希望这能有所帮助。