[wp-trac] [WordPress Trac] #49841: wp_get_attachment_url does not return a url

WordPress Trac noreply at wordpress.org
Tue Jun 2 16:47:11 UTC 2020


#49841: wp_get_attachment_url does not return a url
-------------------------------+------------------------------
 Reporter:  hughie.molloy      |       Owner:  (none)
     Type:  defect (bug)       |      Status:  new
 Priority:  normal             |   Milestone:  Awaiting Review
Component:  Media              |     Version:  5.4
 Severity:  normal             |  Resolution:
 Keywords:  reporter-feedback  |     Focuses:
-------------------------------+------------------------------

Comment (by hughie.molloy):

 Hi John,

 Sorry for the delay. We are using code like the following

 {{{#!php
 <?php
     /**
      * @return int|\WP_Error
      */
     public static function attachImageToPost(int $post_id, string
 $local_filepath, string $title, bool $generate_metadata = true)
     {
         $image_id = static::insertAttachment($title, $local_filepath,
 $post_id, $generate_metadata);
         if (!$image_id instanceof \WP_Error) {
             $image_url = wp_get_attachment_url($image_id);
             update_post_meta($image_id, 'guid', $image_url);
         }

         return $image_id;
     }

     /**
      * @return int|\WP_Error
      */
     protected static function insertAttachment(string $title, string
 $path, int $post_id, bool $generate_metadata = false)
     {
         if (!function_exists('wp_generate_attachment_metadata')) {
             require_once(ABSPATH . 'wp-admin/includes/media.php');
             require_once(ABSPATH . 'wp-admin/includes/file.php');
             require_once(ABSPATH . 'wp-admin/includes/image.php');
         }

         $att_id = wp_insert_attachment([
             'post_content'      => '',
             'post_title'        => $title,
             'post_status'       => 'inherit',
             'post_mime_type'    => 'image/jpg'
         ], $path, $post_id);

         if ($generate_metadata && !$att_id instanceof \WP_Error) {
             $att_meta = wp_generate_attachment_metadata($att_id, $path);
             wp_update_attachment_metadata($att_id, $att_meta);
         }

         return $att_id;
     }
 }}}

 Basically is you have an image somewhere locally with an unescaped file
 name wp_insert_attachment does not correct the path/image name and when
 you can the file it is not escaped properly.

-- 
Ticket URL: <https://core.trac.wordpress.org/ticket/49841#comment:4>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list