settings = Plugin::get_settings( 'posts' );
add_filter( 'adminease_settings_fields', [ $this, 'adminease_settings_fields' ] );
if( !current_user_can( 'edit_posts' ) ) {
return;
}
if( empty( $this->settings['enable_posts_metadata_box'] ) ) {
return;
}
add_action( 'init', [ $this, 'init' ] );
add_action( 'admin_enqueue_scripts', [ $this, 'admin_enqueue_scripts' ] );
add_action( 'admin_footer', [ $this, 'render_modal' ] );
add_action( 'wp_ajax_adminease_get_post_metadata', [ $this, 'ajax_get_post_metadata' ] );
add_action( 'wp_ajax_adminease_update_post_metadata', [ $this, 'ajax_update_post_metadata' ] );
add_action( 'wp_ajax_adminease_delete_post_metadata', [ $this, 'ajax_delete_post_metadata' ] );
}
/**
* Initialize post types on init hook to ensure all custom post types are registered.
*/
public function init() {
$this->post_types = apply_filters( 'adminease_posts_metadata_box_allowed_post_types', Utils::get_post_types( [ 'base', 'media' ] ) );
add_action( 'add_meta_boxes', [ $this, 'add_meta_boxes' ] );
}
/**
* Modifies and returns the settings fields for admin security features.
*
* @param array $fields The existing configuration fields to be updated with additional options.
*
* @return array The updated configuration fields, including the option to add metadata boxes to posts.
*/
public function adminease_settings_fields( array $fields ): array {
$fields['posts']['fields'][] = [
'type' => 'switch',
'id' => 'enable-posts-metadata-box',
'name' => 'adminease[posts][enable_posts_metadata_box]',
'value' => $this->settings['enable_posts_metadata_box'] ?? false,
'label_class' => 'pwp-switch',
'input_class' => 'pwp-field-input toggle-field',
'label' => __( 'Enable Posts Metadata Box', 'adminease' ),
'risk' => 'safe',
'description' => __( 'Enable a metadata box on post edit screens to view and manage custom fields easily. In addition, it adds image sizes to images in the media library.', 'adminease' ),
];
return $fields;
}
/**
* Registers the meta box for allowed post types.
*
* @return void
*/
public function add_meta_boxes(): void {
foreach( $this->post_types as $post_type_key => $post_type ) {
if( 'shop_order' === $post_type_key ) {
$post_type_key = 'woocommerce_page_wc-orders';
} elseif( 'shop_subscription' === $post_type_key ) {
$post_type_key = 'woocommerce_page_wc-orders--shop_subscription';
}
add_meta_box(
'adminease-posts-metadata-box',
__( 'Post Metadata', 'adminease' ),
[ $this, 'render_metabox' ],
$post_type_key,
'normal',
);
}
}
/**
* Renders the meta box content.
*
* @param $post_or_order
*
* @return void
*/
public function render_metabox( $post_or_order ): void {
if( $post_or_order instanceof WP_Post ) {
$post_id = $post_or_order->ID;
} elseif( is_object( $post_or_order ) && method_exists( $post_or_order, 'get_id' ) ) {
$post_id = $post_or_order->get_id();
} else {
$post_id = 0;
}
if( !$post_id ) {
echo '
';
esc_html_e( 'Please save this post first to manage metadata.', 'adminease' );
echo '
';
return;
}
$this->rendered_post_id = $post_id;
?>
` isn't discarded by the browser.
*
* @return void
*/
public function render_modal(): void {
if( null === $this->rendered_post_id ) {
return;
}
?>
post_type, array_keys( $this->post_types ) ) ) {
return;
}
wp_enqueue_style(
ADMINEASE_NAME . 'PostsMetadataBox',
ADMINEASE_PLUGIN_URL . 'assets/css/AdminEasePostsMetadataBox.css',
[ ADMINEASE_NAME . 'NativeBox' ],
filemtime( ADMINEASE_DIR . 'assets/css/AdminEasePostsMetadataBox.css' )
);
wp_enqueue_script(
ADMINEASE_NAME . 'PostsMetadataBox',
ADMINEASE_PLUGIN_URL . 'assets/js/AdminEasePostsMetadataBox.js',
[ 'jquery' ],
filemtime( ADMINEASE_DIR . 'assets/js/AdminEasePostsMetadataBox.js' ),
true
);
wp_localize_script(
ADMINEASE_NAME . 'PostsMetadataBox',
ADMINEASE_NAME . 'PostsMetadataBoxAjaxObj',
[
'ajaxUrl' => admin_url( 'admin-ajax.php' ),
'security' => [
'getPostMetadata' => wp_create_nonce( 'adminease_get_post_metadata' ),
'updatePostMetadata' => wp_create_nonce( 'adminease_update_post_metadata' ),
'deletePostMetadata' => wp_create_nonce( 'adminease_delete_post_metadata' ),
],
'i18n' => [
'metadataModalTitleEdit' => esc_html__( 'Edit Metadata', 'adminease' ),
'metadataModalTitleAdd' => esc_html__( 'Add New Metadata', 'adminease' ),
'metadataConfirmDelete' => esc_html__( 'Are you sure you want to delete this metadata?', 'adminease' ),
'metadataLoadError' => esc_html__( 'Failed to load metadata. Please refresh the page and try again.', 'adminease' ),
'metadataSaveError' => esc_html__( 'Failed to save metadata. Please try again.', 'adminease' ),
'metadataDeleteError' => esc_html__( 'Failed to delete metadata. Please try again.', 'adminease' ),
'metadataSaveSuccess' => esc_html__( 'Metadata saved successfully.', 'adminease' ),
'metadataDeleteSuccess' => esc_html__( 'Metadata deleted successfully.', 'adminease' ),
'metadataKeyRequired' => esc_html__( 'Meta key is required.', 'adminease' ),
'metadataNoMetadata' => esc_html__( 'No metadata found for this post.', 'adminease' ),
'metadataEdit' => esc_html__( 'Edit', 'adminease' ),
'metadataDelete' => esc_html__( 'Delete', 'adminease' ),
'metadataInvalidJSON' => esc_html__( 'Invalid JSON format. Please check your value.', 'adminease' ),
'metadataLoading' => esc_html__( 'Loading metadata...', 'adminease' ),
'metadataTableHeaderKey' => esc_html__( 'Meta Key', 'adminease' ),
'metadataTableHeaderValue' => esc_html__( 'Meta Value', 'adminease' ),
'metadataTableHeaderActions' => esc_html__( 'Actions', 'adminease' ),
'metadataProtectedKey' => esc_html__( 'Protected meta key', 'adminease' ),
'metadataSearch' => esc_html__( 'Search metadata...', 'adminease' ),
'metadataSortAZ' => esc_html__( 'Sort A-Z', 'adminease' ),
'metadataSortZA' => esc_html__( 'Sort Z-A', 'adminease' ),
'metadataNoResults' => esc_html__( 'No metadata found matching your search.', 'adminease' ),
'metadataImageSize' => esc_html__( 'Image size', 'adminease' ),
'metadataReadOnly' => esc_html__( 'Read-only', 'adminease' ),
],
]
);
}
/**
* Adds localization data for JavaScript.
*
* @param array $data Existing localization data.
*
* @return array Modified localization data.
*/
public function adminease_localize_script( array $data ): array {
$data['security']['getPostMetadata'] = wp_create_nonce( 'adminease_get_post_metadata' );
$data['security']['updatePostMetadata'] = wp_create_nonce( 'adminease_update_post_metadata' );
$data['security']['deletePostMetadata'] = wp_create_nonce( 'adminease_delete_post_metadata' );
$data['i18n']['metadataLoadError'] = esc_html__( 'Failed to load metadata. Please refresh the page.', 'adminease' );
$data['i18n']['metadataUpdateSuccess'] = esc_html__( 'Metadata updated successfully.', 'adminease' );
$data['i18n']['metadataUpdateError'] = esc_html__( 'Failed to update metadata. Please try again.', 'adminease' );
$data['i18n']['metadataDeleteConfirm'] = esc_html__( 'Are you sure you want to delete this metadata?', 'adminease' );
$data['i18n']['metadataDeleteSuccess'] = esc_html__( 'Metadata deleted successfully.', 'adminease' );
$data['i18n']['metadataDeleteError'] = esc_html__( 'Failed to delete metadata. Please try again.', 'adminease' );
$data['i18n']['metadataKeyRequired'] = esc_html__( 'Meta key is required.', 'adminease' );
$data['i18n']['metadataNoMetadata'] = esc_html__( 'No metadata found for this post.', 'adminease' );
$data['i18n']['metadataAddNew'] = esc_html__( 'Add New Metadata', 'adminease' );
$data['i18n']['metadataEdit'] = esc_html__( 'Edit Metadata', 'adminease' );
$data['i18n']['metadataInvalidJson'] = esc_html__( 'Invalid JSON format in meta value.', 'adminease' );
return $data;
}
/**
* AJAX handler to get post metadata.
*
* @return void
*/
public function ajax_get_post_metadata(): void {
if( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'adminease_get_post_metadata' ) ) {
wp_send_json_error( [ 'message' => esc_html__( 'Security check failed. Refresh the page and try again.', 'adminease' ) ] );
}
$post_id = isset( $_POST['post_id'] ) ? absint( $_POST['post_id'] ) : 0;
if( !$post_id || !current_user_can( 'edit_post', $post_id ) ) {
wp_send_json_error( [ 'message' => esc_html__( 'Invalid post or insufficient permissions.', 'adminease' ) ] );
}
$post_type = get_post_type( $post_id );
$all_meta = [];
if( function_exists( 'wc_get_order' ) && in_array( $post_type, [ 'shop_order', 'shop_subscription', 'shop_order_placehold' ], true ) ) {
$wc_object = wc_get_order( $post_id );
if( $wc_object ) {
$meta_data = $wc_object->get_meta_data();
foreach( $meta_data as $meta ) {
$key = $meta->key;
$all_meta[ $key ] = [ $meta->value ];
}
}
} elseif( function_exists( 'wc_get_product' ) && 'product' === $post_type ) {
$wc_product = wc_get_product( $post_id );
if( $wc_product ) {
$meta_data = $wc_product->get_meta_data();
foreach( $meta_data as $meta ) {
$key = $meta->key;
$all_meta[ $key ] = [ $meta->value ];
}
}
} else {
$all_meta = get_post_meta( $post_id );
}
$metadata = [];
foreach( $all_meta as $key => $values ) {
$value = $values[0] ?? '';
$display_value = $this->format_meta_value( $value );
$metadata[] = [
'key' => $key,
'value' => $value,
'display_value' => $display_value,
'is_serialized' => is_serialized( $value ),
'is_protected' => substr( $key, 0, 1 ) === '_',
];
}
if( 'attachment' === $post_type ) {
$image_sizes = $this->get_image_size_metadata( $post_id );
$metadata = array_merge( $metadata, $image_sizes );
}
wp_send_json_success( [ 'metadata' => $metadata ] );
}
/**
* AJAX handler to update post metadata.
*
* @return void
*/
public function ajax_update_post_metadata(): void {
if( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'adminease_update_post_metadata' ) ) {
wp_send_json_error( [ 'message' => esc_html__( 'Security check failed. Refresh the page and try again.', 'adminease' ) ] );
}
$post_id = isset( $_POST['post_id'] ) ? absint( $_POST['post_id'] ) : 0;
$meta_key = isset( $_POST['meta_key'] ) ? sanitize_text_field( wp_unslash( $_POST['meta_key'] ) ) : '';
$meta_value = isset( $_POST['meta_value'] ) ? wp_unslash( $_POST['meta_value'] ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
$original_key = isset( $_POST['original_key'] ) ? sanitize_text_field( wp_unslash( $_POST['original_key'] ) ) : '';
if( !$post_id || !current_user_can( 'edit_post', $post_id ) ) {
wp_send_json_error( [ 'message' => esc_html__( 'Invalid post or insufficient permissions.', 'adminease' ) ] );
}
if( empty( $meta_key ) ) {
wp_send_json_error( [ 'message' => esc_html__( 'Meta key is required.', 'adminease' ) ] );
}
if( strpos( $meta_key, '_image_size_' ) === 0 || strpos( $original_key, '_image_size_' ) === 0 ) {
wp_send_json_error( [ 'message' => esc_html__( 'Image size metadata cannot be edited.', 'adminease' ) ] );
}
$processed_value = $this->process_meta_value( $meta_value );
$post_type = get_post_type( $post_id );
if( function_exists( 'wc_get_order' ) && in_array( $post_type, [ 'shop_order', 'shop_subscription', 'shop_order_placehold' ], true ) ) {
$wc_object = wc_get_order( $post_id );
if( $wc_object ) {
if( !empty( $original_key ) && $original_key !== $meta_key ) {
$wc_object->delete_meta_data( $original_key );
}
$wc_object->update_meta_data( $meta_key, $processed_value );
$wc_object->save();
}
} elseif( function_exists( 'wc_get_product' ) && 'product' === $post_type ) {
$wc_product = wc_get_product( $post_id );
if( $wc_product ) {
if( !empty( $original_key ) && $original_key !== $meta_key ) {
$wc_product->delete_meta_data( $original_key );
}
$wc_product->update_meta_data( $meta_key, $processed_value );
$wc_product->save();
}
} else {
if( !empty( $original_key ) && $original_key !== $meta_key ) {
delete_post_meta( $post_id, $original_key );
}
}
update_post_meta( $post_id, $meta_key, $processed_value );
wp_send_json_success( [ 'message' => esc_html__( 'Metadata updated successfully.', 'adminease' ) ] );
}
/**
* AJAX handler to delete post metadata.
*
* @return void
*/
public function ajax_delete_post_metadata(): void {
if( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'adminease_delete_post_metadata' ) ) {
wp_send_json_error( [ 'message' => esc_html__( 'Security check failed. Refresh the page and try again.', 'adminease' ) ] );
}
$post_id = isset( $_POST['post_id'] ) ? absint( $_POST['post_id'] ) : 0;
$meta_key = isset( $_POST['meta_key'] ) ? sanitize_text_field( wp_unslash( $_POST['meta_key'] ) ) : '';
if( !$post_id || !current_user_can( 'edit_post', $post_id ) ) {
wp_send_json_error( [ 'message' => esc_html__( 'Invalid post or insufficient permissions.', 'adminease' ) ] );
}
if( empty( $meta_key ) ) {
wp_send_json_error( [ 'message' => esc_html__( 'Meta key is required.', 'adminease' ) ] );
}
if( strpos( $meta_key, '_image_size_' ) === 0 ) {
wp_send_json_error( [ 'message' => esc_html__( 'Image size metadata cannot be deleted.', 'adminease' ) ] );
}
$post_type = get_post_type( $post_id );
if( function_exists( 'wc_get_order' ) && in_array( $post_type, [ 'shop_order', 'shop_subscription' ], true ) ) {
$wc_object = wc_get_order( $post_id );
if( $wc_object ) {
$wc_object->delete_meta_data( $meta_key );
$wc_object->save();
}
} elseif( function_exists( 'wc_get_product' ) && 'product' === $post_type ) {
$wc_product = wc_get_product( $post_id );
if( $wc_product ) {
$wc_product->delete_meta_data( $meta_key );
$wc_product->save();
}
} else {
delete_post_meta( $post_id, $meta_key );
}
wp_send_json_success( [ 'message' => esc_html__( 'Metadata deleted successfully.', 'adminease' ) ] );
}
/**
* Formats meta value for display.
*
* @param mixed $value The meta value.
*
* @return string Formatted value.
*/
private function format_meta_value( $value ): string {
$unserialized = maybe_unserialize( $value );
if( is_array( $unserialized ) || is_object( $unserialized ) ) {
return wp_json_encode( $unserialized, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
}
return (string) $value;
}
/**
* Processes meta value from form input.
* Detects JSON and converts it to proper PHP structure.
*
* @param mixed $value The input value.
*
* @return mixed Processed value.
*/
private function process_meta_value( $value ) {
if( is_serialized( $value ) ) {
return $value;
}
$decoded = json_decode( $value, true );
if( json_last_error() === JSON_ERROR_NONE && ( is_array( $decoded ) || is_object( $decoded ) ) ) {
return $decoded;
}
return sanitize_textarea_field( $value );
}
/**
* Gets image size metadata for an attachment.
* Returns an array of virtual metadata entries for each registered image size.
*
* @param int $attachment_id The attachment post ID.
*
* @return array Array of image size metadata entries.
*/
private function get_image_size_metadata( int $attachment_id ): array {
$metadata = [];
$mime_type = get_post_mime_type( $attachment_id );
if( !$mime_type || 0 !== strpos( $mime_type, 'image/' ) ) {
return $metadata;
}
$image_sizes = get_intermediate_image_sizes();
$image_sizes[] = 'full';
foreach( $image_sizes as $size_name ) {
$image_data = wp_get_attachment_image_src( $attachment_id, $size_name );
if( $image_data && !empty( $image_data[0] ) ) {
$url = $image_data[0];
$width = $image_data[1] ?? 0;
$height = $image_data[2] ?? 0;
$display_value = $url;
if( $width && $height ) {
$display_value .= " ({$width}x{$height})";
}
$metadata[] = [
'key' => '_image_size_' . $size_name,
'value' => $url,
'display_value' => $display_value,
'is_serialized' => false,
'is_protected' => true,
'is_image_size' => true,
'is_readonly' => true,
];
}
}
return $metadata;
}
}