wallabi-es / image-focus

Image Focus: Crop your WordPress images by focus point
18 stars 9 forks source link

Fix for WordPress 5.2.3+ #46

Open Djules opened 4 years ago

Djules commented 4 years ago

The library no longer works since WordPress 5.2.3, as they remove the 'data-id' attribute used to retrieved the attachment_id of AJAX requests.

I'm not sure if it will be added again, but here is a hotfix to add id back so the library can work again. Add this code anywhere in your function.php or any PHP file you want:

/**
 * Restore data attribute with attachment_id for Image Focus plugin.
 */
add_action( 'wp_enqueue_media', 'imagefocus_media_hotfix' );
function imagefocus_media_hotfix() {
    if ( is_admin() ) {
        wp_add_inline_script( 'media-views', 'wp.media.view.Attachment.Details=wp.media.view.Attachment.Details.extend({attributes:function(){return{"data-id":this.model.get("id")}}});' );
    }
}
AndreaJ-UGroup commented 3 years ago

Thanks for the hot fix, but it no longer works as of WordPress v5.7.2. The cropper appears to work, but the image file doesn't exist afterward.

michaelw85 commented 1 year ago

For anyone stumbling upon this topic and still using this library. I'm currently on the latest WP (6.3) and I solved fetching the ID with the following code:

  const url = new URL(
      window.location.href.includes('?item')
          ? window.location.href
          : document.querySelector('#wp-admin-canonical').href
  );
  const urlParams = new URLSearchParams(url.search);
  base.attachment._id = urlParams.get('item');

I'm not entirely sure the canonical fallback is required but for some reason, I had a situation where the current URL did not contain the item ID so I added this fallback to be sure. I can't reproduce the situation so it might have been caused by an error. Better to be sure than sorry I guess.