wordpress-plugin icon indicating copy to clipboard operation
wordpress-plugin copied to clipboard

Add Start and Pause Functions for backend development. Pause compress…

Open senica opened this issue 8 years ago • 2 comments

…ion.

I have a function in my functions.php file that retrieves images from vimeo. I know those images are already compressed, so I don't need tinypng to touch them.

I'm using this like:

function es_save_product( $post_id ){

  global $tiny_plugin;
  $tiny_plugin->pause(); // This stops compression

  $post_meta = get_post_meta($post_id);
  $prev = $post_meta['vimeo_thumb_set'];

  $vimeo = $post_meta['vimeo_url'];

  // We do not have the field vimeo_url set, don't try and get thumbnail
  if(!is_array($vimeo) || empty($vimeo[0])) return;

  $did_match = preg_match('/^https?:\/\/[^\/]+\/(.*)$/', $vimeo[0], $matches);

  // Invalid vimeo url, so we can't get the thumbnail anyway
  if(!$did_match) return;

  $id = $matches[1];
  $prev = $post_meta['vimeo_thumb_set'];

  // We've already set the thumbnail with this vimeo id
  if(is_array($prev) && $prev[0] == $id) return;

  $c = curl_init('http://vimeo.com/api/v2/video/'.$id.'.json');
  curl_setopt($c, CURLOPT_VERBOSE, 1);
  curl_setopt($c, CURLOPT_FOLLOWLOCATION, true); // follow redirects
  curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
  $page = curl_exec($c);
  curl_close($c);
  $json = json_decode($page);

  // Invalid response from vimeo
  if($json === null) return;

  // Allow us to get this data in the future
  update_post_meta($post_id, 'vimeo_meta', $json);
  $thumb = $json[0]->thumbnail_large;
  $desc = $json[0]->description;

  // Unexpected response from vimeo
  if(empty($thumb)) return;

  function attach_vimeo($att_id){
    global $post_id;
    update_post_meta($post_id,'_thumbnail_id', $att_id);
  }

  add_action('add_attachment','attach_vimeo');

  $src = media_sideload_image($thumb, $post_id, $desc, 'src');

  remove_action('add_attachment','attach_vimeo');

  // Image never uploaded properly
  if(empty($src) || is_wp_error( $src )) return;

  // Say that we've set the thumbnail with vimeo video id
  update_post_meta($post_id, 'vimeo_thumb_set', $id);

  $tiny_plugin->start(); // This will restart it for any other handlers that follow

}
add_action( 'save_post', 'es_save_product', 10, 3 );

senica avatar Jul 06 '16 00:07 senica

As per our conversation, I did not do any tests on this. Sorry :/ I was running into a docker error.

senica avatar Jul 06 '16 00:07 senica

Awesome, thanks! We'll merge this, but probably want to rename the methods to reflect that the optimisation is only disabled for the current request / script. The current master is in a state of flux, but it will settle down soon and we will make this part of the upcoming release.

rolftimmermans avatar Jul 06 '16 09:07 rolftimmermans