1

I am building a plugin that retrieves YouTube videos for a given channel and stores them in the database. Once they are safe in the database I create a REST point which I can access than any time to have the list ready.

The issue here is how they are stored and retrieved via REST afterwards.

Retrieving the videos:

    $response = wp_remote_request( 'https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId='.$playlist_id.'&key='.$api_key.'&order=date&maxResults=25',
    array(
        'method'     => 'GET'
      )
    );

    // get response and JSON decode it
    $json = wp_remote_retrieve_body($response);
    $json_decoded = json_decode($json, true);

    // if we have any items update the db with those results
    if ( isset ( $json_decoded['items'] )) {
      $videos['json'] = $json_decoded['items'];
      update_option( 'wpc_ylp_videos', $videos );
    }

I am using json_decode() and placing them into the db with update options.

Later I am making the REST point available and retrieving them:

// REST END POINT FOR THE VIDEOS
function wpc_ylp_rest_videos( ) {


  $videos = get_option( 'wpc_ylp_videos' );
  if( isset( $videos[ 'json' ] ) ) {
    $json = $videos['json'];
    echo json_encode($json);
  }

}

add_action( 'rest_api_init', function () {
  register_rest_route( 'wpc_ylp/v2', '/videos', array(
    'methods' => 'GET',
    'callback' => 'wpc_ylp_rest_videos',
  ) );
} );

So I am using json_encode(). I am getting a response visiting the REST API, but my issue is the formatting as per this example:

Getting time from the server, no need to check, use the saved JSON list in the db539<br>[{"kind":"youtube#playlistItem","etag":"\"p4V

My questions are the following: 1. Why do I get the Getting time from the server... part at the start of what is otherwise my almost valid reply from the endpoint? 2. Why is the endpoint not incorrect JSON format?

  • This appears to be a follow up question to wordpress.stackexchange.com/questions/354483/…, which I answered and explained that you've not implemented the endpoint correctly, you've made the same mistake people who echo in shortcodes make – Tom J Nowell Dec 12 '19 at 20:34
  • Also, you shouldn't save arrays and objects to options, they'll get PHP serialised, you'd be better off JSON encoding them beforehand then decoding. Deserialising things via PHP opens you up to object deserialisation attacks – Tom J Nowell Dec 12 '19 at 20:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.