Skip to content

Instantly share code, notes, and snippets.

@jeherve
Created February 28, 2017 22:08
Show Gist options
  • Save jeherve/b0c9d7c3897391c906bc3702fc7ce2d6 to your computer and use it in GitHub Desktop.
Save jeherve/b0c9d7c3897391c906bc3702fc7ce2d6 to your computer and use it in GitHub Desktop.
<?php
/**
* Plugin Name: Add a list of Jetpack related posts to the bottom of each post in the Rest API Posts Embeds shortcode.
* Plugin URI: http://jeremy.hu/
* Description: Add a list of Jetpack related posts to the bottom of each post in the Rest API Posts Embeds shortcode.
* Author: Jeremy Herve
* Version: 1.0.0
* Author URI: https://jeremy.hu
* License: GPL2+
*/
/**
* Add a list of Jetpack related posts to the bottom of each post in the Rest API Posts Embeds shortcode.
*
* @see https://wordpress.org/support/topic/specific-post-type-not-working-with-wpapitrue/
*
* @param string $article Article layout.
* @param object $single_post Array of information about the post.
*/
function jeherve_add_color_post( $article, $single_post ) {
// Build our site URL.
$parsed_url = parse_url( $single_post->guid->rendered );
if ( isset( $parsed_url['scheme'], $parsed_url['host'] ) ) {
$site_url = $parsed_url['scheme'] . '://' . $parsed_url['host'];
} else {
return $article;
}
$post_rest_url = sprintf(
'%1$s/wp-json/wp/v2/posts/%2$d',
esc_url( $site_url ),
absint( $single_post->id )
);
// Hash that post URL to cache it in a transient.
$post_rest_hash = substr( md5( $post_rest_url ), 0, 21 );
// Look for data in our transient.
$data_from_cache = get_transient( 'jeherve_post_embed_' . $post_rest_hash );
if ( false === $data_from_cache ) {
$post_data = wp_remote_get( esc_url_raw( $post_rest_url ) );
if (
is_wp_error( $post_data )
|| 200 != $post_data['response']['code']
|| empty( $post_data['body'] )
) {
return $article;
}
$post_data_body = wp_remote_retrieve_body( $post_data );
$post_info = json_decode( $post_data_body );
// Cache the result.
set_transient( 'jeherve_post_embed_' . $post_rest_hash, $post_info, 10 * MINUTE_IN_SECONDS );
} else {
$post_info = $data_from_cache;
}
// Do we have an array of Related Posts?
if ( is_array( $post_info->{'jetpack-related-posts'} ) && ! empty( $post_info->{'jetpack-related-posts'} ) ) {
$related_posts = '<ul>';
// Loop through each related post to build an unordered list.
foreach ( $post_info->{'jetpack-related-posts'} as $related_post ) {
$related_posts .= sprintf(
'<li><a href="%1$s">%2$s</a></li>',
esc_url( $related_post->url ),
esc_html( $related_post->title )
);
}
$related_posts .= '</ul>';
// Append our list of related posts to each article.
return $article . $related_posts;
}
// Final fallback.
return $article;
}
add_filter( 'jeherve_post_embed_article_layout', 'jeherve_add_color_post', 20, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment