diff --git a/community-listings/includes/Admin/ProviderListingsMetaBox.php b/community-listings/includes/Admin/ProviderListingsMetaBox.php new file mode 100644 index 0000000..9936979 --- /dev/null +++ b/community-listings/includes/Admin/ProviderListingsMetaBox.php @@ -0,0 +1,303 @@ +ID, 'listing_type', true ); + + if ( 'city' !== $listing_type ) { + return; + } + + \add_meta_box( + 'provider-listings-meta-box', + \__( 'Provider Listings', 'community-listings' ), + array( $this, 'render_meta_box' ), + 'community', + 'normal', + 'high' + ); + } + + /** + * Render the Provider Listings meta box. + * + * @since 2.2.5 + * + * @param \WP_Post $post Post object. + * @return void + */ + public function render_meta_box( \WP_Post $post ): void { + $raw_json = \get_post_meta( $post->ID, 'provider_listings', true ); + $raw_json = \is_string( $raw_json ) ? $raw_json : ''; + + $formatted_json = $raw_json; + $decoded_json = null; + + if ( '' !== $raw_json ) { + $decoded_json = \json_decode( $raw_json, true ); + + if ( \JSON_ERROR_NONE === \json_last_error() ) { + $pretty_json = \json_encode( $decoded_json, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_UNICODE ); + + if ( false !== $pretty_json ) { + $formatted_json = $pretty_json; + } + } + } + + $provider_count = \is_array( $decoded_json ) && \array_is_list( $decoded_json ) ? \count( $decoded_json ) : 0; + $byte_count = \strlen( $formatted_json ); + $nonce = \wp_create_nonce( self::NONCE_ACTION ); + ?> + + +
+ bytes + ยท + +
+ + + update( + $wpdb->postmeta, + array( 'meta_value' => $json_string ), + array( + 'post_id' => $post_id, + 'meta_key' => 'provider_listings', + ), + array( '%s' ), + array( '%d', '%s' ) + ); + + if ( false === $updated ) { + return; + } + + if ( 0 === $updated && ! \metadata_exists( 'post', $post_id, 'provider_listings' ) ) { + $wpdb->insert( + $wpdb->postmeta, + array( + 'post_id' => $post_id, + 'meta_key' => 'provider_listings', + 'meta_value' => $json_string, + ), + array( '%d', '%s', '%s' ) + ); + } + } + + /** + * Add invalid JSON flag to redirect URL. + * + * @since 2.2.5 + * + * @param string $location Redirect URL. + * @return string + */ + public function append_invalid_json_query_arg( string $location ): string { + \remove_filter( 'redirect_post_location', array( $this, __FUNCTION__ ) ); + return \add_query_arg( self::INVALID_JSON_QUERY_ARG, '1', $location ); + } + + /** + * Render invalid JSON admin notice. + * + * @since 2.2.5 + * + * @return void + */ + public function render_invalid_json_notice(): void { + $screen = \function_exists( 'get_current_screen' ) ? \get_current_screen() : null; + if ( ! $screen || 'community' !== $screen->post_type ) { + return; + } + + $invalid_flag = $_GET[ self::INVALID_JSON_QUERY_ARG ] ?? ''; + $invalid_flag = \is_string( $invalid_flag ) ? \sanitize_text_field( \wp_unslash( $invalid_flag ) ) : ''; + if ( '1' !== $invalid_flag ) { + return; + } + ?> +