Skip to content

Instantly share code, notes, and snippets.

@PeterBooker
Last active September 11, 2017 12:23
Show Gist options
  • Save PeterBooker/b7c96d2fbdff2e89b67ba47ca3ccb214 to your computer and use it in GitHub Desktop.
Save PeterBooker/b7c96d2fbdff2e89b67ba47ca3ccb214 to your computer and use it in GitHub Desktop.
Get and store Posts from another site using the WP REST API
<?php
function prefix_get_newsletter_posts() {
// Get the cached data if available, if not fetch it using the WP REST API
if ( false === ( $newsletter_posts_data = get_transient( 'prefix_newsletter_posts' ) ) ) {
// Tag ID for the Posts you want from the Newsletter site.
$tag_id = 12;
$response = wp_remote_get( 'http://newsletter.site.com/wp-json/wp/v2/posts?tags=' . $tag_id );
if ( is_wp_error( $response ) ) {
// HTTP Request Failed
return false;
} else {
$body = wp_remote_retrieve_body( $response );
$newsletter_posts = json_decode( $body );
if ( isset( $newsletter_posts[0]->link ) ) {
// Store the data for 30mins
// Edit this if you want to change how long the data is cached for.
set_transient( 'prefix_newsletter_posts', $body, 30 * MINUTE_IN_SECONDS );
}
return $newsletter_posts;
}
}
$newsletter_posts = json_decode( $newsletter_posts_data );
return $newsletter_posts;
}
function the_newsletter_posts() {
$newsletter_posts = get_newsletter_posts(); ?>
if ( $posts ) {
echo '<ul>';
foreach ( $newsletter_posts as $news_post ) { ?>
<li><a href="<?php echo esc_url( $news_post->link ); ?>" title="<?php echo esc_attr( $news_post->title->rendered ); ?>"><?php echo esc_html( $news_post->title->rendered ); ?></a></li>
<?php }
echo '</ul>';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment