__( 'Displays a list of recent posts from another WordPress.com or Jetpack-enabled blog.', 'jetpack' ), ) ); } /** * Expiring transients have a name length maximum of 45 characters, * so this function returns an abbreviated MD5 hash to use instead of * the full URI. */ public function get_site_hash( $site ) { return substr( md5( $site ), 0, 21 ); } public function get_site_info( $site ) { $site_hash = $this->get_site_hash( $site ); $data_from_cache = get_transient( 'display_posts_site_info_' . $site_hash ); if ( false === $data_from_cache ) { $response = wp_remote_get( sprintf( 'https://public-api.wordpress.com/rest/v1/sites/%s', urlencode( $site ) ) ); set_transient( 'display_posts_site_info_' . $site_hash, $response, 10 * MINUTE_IN_SECONDS ); } else { $response = $data_from_cache; } if ( is_wp_error( $response ) ) { return false; } $site_info = json_decode( $response ['body'] ); if ( ! isset( $site_info->ID ) ) { return false; } return $site_info; } /* * Set up the widget display on the front end */ public function widget( $args, $instance ) { $title = apply_filters( 'widget_title', $instance['title'] ); wp_enqueue_style( 'jetpack_display_posts_widget', plugins_url( 'wordpress-post-widget/style.css', __FILE__ ) ); $site_info = $this->get_site_info( $instance['url'] ); echo $args['before_widget']; if ( false === $site_info ) { echo '
' . __( 'We cannot load blog data at this time.', 'jetpack' ) . '
'; echo $args['after_widget']; return; } if ( ! empty( $title ) ) { echo $args['before_title'] . esc_html( $title . ': ' . $site_info->name ) . $args['after_title']; } else { echo $args['before_title'] . esc_html( $site_info->name ) . $args['after_title']; } $site_hash = $this->get_site_hash( $instance['url'] ); $data_from_cache = get_transient( 'display_posts_post_info_' . $site_hash ); if ( false === $data_from_cache ) { $response = wp_remote_get( sprintf( 'https://public-api.wordpress.com/rest/v1/sites/%d/posts/', $site_info->ID ) ); set_transient( 'display_posts_post_info_' . $site_hash, $response, 10 * MINUTE_IN_SECONDS ); } else { $response = $data_from_cache; } if ( is_wp_error( $response ) ) { echo '' . __( 'We cannot load blog data at this time.', 'jetpack' ) . '
'; echo $args['after_widget']; return; } $posts_info = json_decode( $response['body'] ); echo '' . __( 'We cannot display posts for this blog.', 'jetpack' ) . '
'; echo '
/>
/>
get_site_info( $instance['url'] ); if ( ! $site_info && 'www.' === substr( $instance['url'], 0, 4 ) ) { $site_info = $this->get_site_info( substr( $instance['url'], 4 ) ); if ( $site_info ) { $instance['url'] = substr( $instance['url'], 4 ); } } $instance['number_of_posts'] = ( ! empty( $new_instance['number_of_posts'] ) ) ? intval( $new_instance['number_of_posts'] ) : ''; $instance['featured_image'] = ( ! empty( $new_instance['featured_image'] ) ) ? true : ''; $instance['show_excerpts'] = ( ! empty( $new_instance['show_excerpts'] ) ) ? true : ''; return $instance; } }