Skip to content

Instantly share code, notes, and snippets.

@Tuarisa
Created January 2, 2018 19:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tuarisa/b9d334566a8ce6d569942aae9180cdde to your computer and use it in GitHub Desktop.
Save Tuarisa/b9d334566a8ce6d569942aae9180cdde to your computer and use it in GitHub Desktop.
Json Extended Fields for json api
<?php
/*
Plugin Name: Json Extended Fields for json api
Author: Tuarisa
Description: Extends json functionality for wordpress REST API
*/
add_action( 'rest_api_init', 'add_custom_to_JSON' );
function add_custom_to_JSON() {
remove_filter( 'the_content', 'removeFirstImg' ); // remove filter, that added in functions php
register_rest_field(
'post',
'image_src',
array(
'get_callback' => 'get_image_src',
'update_callback' => null,
'schema' => null,
)
);
}
function get_image_src( $object, $field_name, $request ) { // first image src (exaclty like now)
$first_img = '';
$output = preg_match_all('/<img.*src="(.*)".*>/isU', $object['content']['raw'], $matches);
$first_img = $matches [1] [0];
if(empty($first_img) || file_exists($first_img)){
$first_img = $object['content']['raw'];
}
return $first_img;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment