Ei kuvausta

ImageAttachment.php 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. /**
  3. * Helper to upload files via the REST API.
  4. *
  5. * @package WooCommerce\Utilities
  6. */
  7. namespace Automattic\WooCommerce\RestApi\Utilities;
  8. /**
  9. * ImageAttachment class.
  10. */
  11. class ImageAttachment {
  12. /**
  13. * Attachment ID.
  14. *
  15. * @var integer
  16. */
  17. public $id = 0;
  18. /**
  19. * Object attached to.
  20. *
  21. * @var integer
  22. */
  23. public $object_id = 0;
  24. /**
  25. * Constructor.
  26. *
  27. * @param integer $id Attachment ID.
  28. * @param integer $object_id Object ID.
  29. */
  30. public function __construct( $id = 0, $object_id = 0 ) {
  31. $this->id = (int) $id;
  32. $this->object_id = (int) $object_id;
  33. }
  34. /**
  35. * Upload an attachment file.
  36. *
  37. * @throws \WC_REST_Exception REST API exceptions.
  38. * @param string $src URL to file.
  39. */
  40. public function upload_image_from_src( $src ) {
  41. $upload = wc_rest_upload_image_from_url( esc_url_raw( $src ) );
  42. if ( is_wp_error( $upload ) ) {
  43. if ( ! apply_filters( 'woocommerce_rest_suppress_image_upload_error', false, $upload, $this->object_id, $images ) ) {
  44. throw new \WC_REST_Exception( 'woocommerce_product_image_upload_error', $upload->get_error_message(), 400 );
  45. } else {
  46. return;
  47. }
  48. }
  49. $this->id = wc_rest_set_uploaded_image_as_attachment( $upload, $this->object_id );
  50. if ( ! wp_attachment_is_image( $this->id ) ) {
  51. /* translators: %s: image ID */
  52. throw new \WC_REST_Exception( 'woocommerce_product_invalid_image_id', sprintf( __( '#%s is an invalid image ID.', 'woocommerce' ), $this->id ), 400 );
  53. }
  54. }
  55. /**
  56. * Update attachment alt text.
  57. *
  58. * @param string $text Text to set.
  59. */
  60. public function update_alt_text( $text ) {
  61. if ( ! $this->id ) {
  62. return;
  63. }
  64. update_post_meta( $this->id, '_wp_attachment_image_alt', wc_clean( $text ) );
  65. }
  66. /**
  67. * Update attachment name.
  68. *
  69. * @param string $text Text to set.
  70. */
  71. public function update_name( $text ) {
  72. if ( ! $this->id ) {
  73. return;
  74. }
  75. wp_update_post(
  76. array(
  77. 'ID' => $this->id,
  78. 'post_title' => $text,
  79. )
  80. );
  81. }
  82. }