如何在WordPress PHP小工具中解析JSON并实时展示?附示例JSON
Got it, let's build a custom WordPress PHP widget that parses your JSON data, handles special characters safely, and displays the content in real-time. I'll walk you through the full implementation with WordPress best practices.
1. Full Widget Implementation
Add this code to your theme's functions.php file or a custom plugin:
<?php /** * Custom JSON Recipe Feed Widget */ class JSON_Feed_Widget extends WP_Widget { /** * Register widget with WordPress. */ function __construct() { parent::__construct( 'json_feed_widget', // Base widget ID esc_html__( 'JSON Recipe Feed', 'text_domain' ), // Widget name array( 'description' => esc_html__( 'Displays recipe content from a JSON feed.', 'text_domain' ), ) // Widget description ); } /** * Front-end display of widget. * * @param array $args Widget wrapper arguments (from theme). * @param array $instance Saved widget settings from admin. */ public function widget( $args, $instance ) { echo $args['before_widget']; // Display widget title if set if ( ! empty( $instance['title'] ) ) { echo $args['before_title'] . apply_filters( 'widget_title', $instance['title'] ) . $args['after_title']; } // Fetch JSON data (replace with your actual feed URL) $json_url = 'YOUR_JSON_FEED_URL_HERE'; $response = wp_remote_get( $json_url ); // Handle HTTP request errors if ( is_wp_error( $response ) || wp_remote_retrieve_response_code( $response ) !== 200 ) { echo '<p>' . esc_html__( 'Failed to load recipe content.', 'text_domain' ) . '</p>'; echo $args['after_widget']; return; } // Parse JSON into an associative array $json_data = json_decode( wp_remote_retrieve_body( $response ), true ); // Validate JSON structure if ( empty( $json_data['status'] ) || $json_data['status'] !== 'ok' || empty( $json_data['articles'] ) ) { echo '<p>' . esc_html__( 'No recipe content available.', 'text_domain' ) . '</p>'; echo $args['after_widget']; return; } // Render the recipe articles echo '<div class="json-feed-articles">'; foreach ( $json_data['articles'] as $article ) { echo '<div class="json-feed-article">'; // Display featured image (if available) if ( ! empty( $article['urlToImage'] ) ) { echo '<img src="' . esc_url( $article['urlToImage'] ) . '" alt="' . esc_attr( $article['title'] ) . '" class="feed-image">'; } // Display title with safe link echo '<h3 class="feed-title"><a href="' . esc_url( $article['url'] ) . '" target="_blank" rel="noopener noreferrer">' . esc_html( $article['title'] ) . '</a></h3>'; // Display author if ( ! empty( $article['author'] ) ) { echo '<p class="feed-author">' . esc_html__( 'By:', 'text_domain' ) . ' ' . esc_html( $article['author'] ) . '</p>'; } // Display description (preserve safe HTML) if ( ! empty( $article['description'] ) ) { echo '<p class="feed-description">' . wp_kses_post( $article['description'] ) . '</p>'; } // Display formatted published date (if available) if ( ! empty( $article['publishedAt'] ) ) { $formatted_date = date_i18n( get_option( 'date_format' ), strtotime( $article['publishedAt'] ) ); echo '<p class="feed-date">' . esc_html( $formatted_date ) . '</p>'; } echo '</div>'; } echo '</div>'; echo $args['after_widget']; } /** * Back-end widget settings form. * * @param array $instance Previously saved settings. */ public function form( $instance ) { $title = ! empty( $instance['title'] ) ? $instance['title'] : esc_html__( 'Recipe Feed', 'text_domain' ); ?> <p> <label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"><?php esc_attr_e( 'Title:', 'text_domain' ); ?></label> <input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>"> </p> <?php } /** * Sanitize settings before saving to database. * * @param array $new_instance New settings submitted. * @param array $old_instance Previous saved settings. * @return array Sanitized settings. */ public function update( $new_instance, $old_instance ) { $instance = array(); $instance['title'] = ( ! empty( $new_instance['title'] ) ) ? sanitize_text_field( $new_instance['title'] ) : ''; return $instance; } } // End JSON_Feed_Widget class // Register the widget with WordPress function register_json_feed_widget() { register_widget( 'JSON_Feed_Widget' ); } add_action( 'widgets_init', 'register_json_feed_widget' ); ?>
2. Key Details Explained
- JSON Fetching: We use
wp_remote_get()instead of rawfile_get_contents()because it's WordPress-native, handles HTTP errors gracefully, and works with caching plugins out of the box. - Special Character Safety:
esc_html()cleans text (titles, authors) to prevent XSS attacks and properly render special characters like”from your sample JSON.wp_kses_post()preserves safe HTML in descriptions while stripping malicious code.esc_url()ensures links and image URLs are valid and secure.
- Fallback Logic: The widget checks for failed requests, invalid JSON structure, and empty article lists, showing user-friendly messages instead of breaking the page.
- Date Localization:
date_i18n()converts the ISO 8601 date from the JSON into your WordPress site's local date format.
3. Example JSON Structure Reference
Here's the sample JSON data this widget is built to parse:
{ "status": "ok", "totalResults": 2, "articles": [ { "source": { "id": "cooking-recepie", "name": "cooking recepie" }, "author": "cooking recepie Staff", "title": "lamb steak", "description": "fffffffffffffffffffffff.”", "url": "http://www.cooking-recepie.net/node/116605", "urlToImage": "https://www.cooking-recepie.net/sites/default/[type]/[nid]/conte-1801-cap-epa.jpg", "publishedAt": "2018-02-02T01:00:00Z" }, { "source": { "id": "cooking-recepie", "name": "cooking recepie" }, "author": "cooking recepie Staff", "title": "Igghhhhhhhhhhhhhhhhhhhh?", "description": "yhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh.", "url": "http://www.cooking-recepie.net/116598/inter-push-lautaro-martinez", "urlToImage": "https://www.cooking-recepie.net/sites/[nid]/Martinez-Lau..." } ] }
4. How to Use
- Replace
YOUR_JSON_FEED_URL_HEREwith the actual URL of your JSON feed. - Go to Appearance > Widgets in your WordPress admin, drag the "JSON Recipe Feed" widget to your desired sidebar, and set a custom title.
内容的提问来源于stack exchange,提问作者1976 Umar
相关产品推荐
相关产品推荐

