Last active
November 30, 2019 05:53
-
-
Save them-es/299d305963018cf66cf9626e79639eb0 to your computer and use it in GitHub Desktop.
WordPress Multiblog: Combine WP-API feeds from different websites and cache the output
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* WordPress "Multiblog" | |
* | |
* Combine multiple WP-API feeds sorted by date and cache the output via Transients API | |
*/ | |
// Cache transients in database: https://codex.wordpress.org/Transients_API | |
$transient = 'wp_api_remote_posts_cache; | |
$content = get_transient( $transient ); // Try to get cached data | |
if ( empty( $content ) ) : | |
$response_mainsite = wp_remote_get( get_rest_url( null, 'wp/v2/posts ) ); | |
$urls = array(); | |
$urls[] = 'https://secondwebsite.com/wp-json/wp/v2/posts'; | |
$urls[] = 'https://thirdwebsite.com/wp-json/wp/v2/posts'; | |
if ( ! is_wp_error( $response_mainsite ) ) : | |
$data_mainsite = json_decode( wp_remote_retrieve_body( $response_mainsite ) ); | |
endif; | |
if ( ! empty( $urls ) ) : | |
$data_mergedsites = array(); | |
foreach ( $urls as $url ) { | |
$response_site = wp_remote_get( $url ); | |
if ( ! is_wp_error( $response_site ) ) : | |
$data_site = json_decode( wp_remote_retrieve_body( $response_site ) ); | |
//print_r( $data_site ); | |
$data_mergedsites = array_merge( $data_mergedsites, $data_site ); | |
endif; | |
} | |
// Merge data from main site with data from other sites | |
$recent_posts = array_merge( $data_mainsite, $data_mergedsites ); | |
// Sort merged data by date | |
usort( $recent_posts, function ( $a, $b ) { | |
return strtotime( $b->date ) - strtotime( $a->date ); | |
} ); | |
else : | |
$recent_posts = $data_mainsite; | |
endif; | |
//print_r( $recent_posts ); | |
if ( ! empty( $recent_posts ) ) : | |
$content .= '<ul class="recentposts">'; | |
$i = 0; | |
foreach ( $recent_posts as $recent_post ) : | |
++$i; | |
// Limit to 10 posts | |
if ( $i <= 10 ) : | |
$content .= '<li>'; | |
$content .= '<h4 class="widget-title"><a href="' . esc_url( $recent_post->link ) . '" rel="bookmark">' . esc_html( $recent_post->title->rendered ) . '</a></h4>'; | |
$content .= '</li>'; | |
endif; | |
endforeach; | |
$content .= '</ul>'; | |
set_transient( $transient, $content, 12 * HOUR_IN_SECONDS ); // Cache data for 1/2 day | |
endif; | |
endif; | |
echo $content; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment