Skip to content

Commit

Permalink
Related Posts: add posts to the WP REST API Post Response.
Browse files Browse the repository at this point in the history
Fixes #3424

To test:
1. Install and activate the WP REST API plugin (v2)
2. Make sure Related Posts are enabled in Jetpack.
3. Visit `http://yoursite.com/wp-json/wp/v2/posts`
4. Look for the new `jetpack-related-posts` field
  • Loading branch information
jeherve authored and Rich Collier committed Aug 29, 2016
1 parent 0a94948 commit abd4971
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions modules/related-posts/jetpack-related-posts.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,9 @@ public function __construct( $blog_id_local, $blog_id_wpcom ) {
if ( ! class_exists( 'Jetpack_Media_Summary' ) ) {
jetpack_require_lib( 'class.media-summary' );
}

// Add Related Posts to the REST API Post response.
add_action( 'rest_api_init', array( $this, 'rest_register_related_posts' ) );
}

/**
Expand Down Expand Up @@ -1282,6 +1285,49 @@ protected function _allow_feature_toggle() {
}
return $this->_allow_feature_toggle;
}

/**
* ===================================================
* FUNCTIONS EXPOSING RELATED POSTS IN THE WP REST API
* ===================================================
*/

/**
* Add Related Posts to the REST API Post response.
*
* @since 4.0.0
*
* @action rest_api_init
* @uses register_rest_field, self::rest_get_related_posts
* @return null
*/
public function rest_register_related_posts() {
register_rest_field( 'post',
'jetpack-related-posts',
array(
'get_callback' => array( $this, 'rest_get_related_posts' ),
'update_callback' => null,
'schema' => null,
)
);
}

/**
* Build an array of Related Posts.
*
* @since 4.0.0
*
* @param array $object Details of current post.
* @param string $field_name Name of field.
* @param WP_REST_Request $request Current request
*
* @uses self::get_for_post_id
*
* @return array
*/
public function rest_get_related_posts( $object, $field_name, $request ) {
return $this->get_for_post_id( $object['id'], array() );
}
}

class Jetpack_RelatedPosts_Raw extends Jetpack_RelatedPosts {
Expand Down

0 comments on commit abd4971

Please sign in to comment.