WP_Import::process_attachment PHP Method

process_attachment() public method

If fetching attachments is enabled then attempt to create a new attachment
public process_attachment ( array $post, string $url ) : integer | WP_Error
$post array Attachment post details from WXR
$url string URL to fetch attachment from
return integer | WP_Error Post ID on success, WP_Error otherwise
        function process_attachment($post, $url)
        {
            if (!$this->fetch_attachments) {
                return new WP_Error('attachment_processing_error', __('Fetching attachments is not enabled', 'wordpress-importer'));
            }
            // if the URL is absolute, but does not contain address, then upload it assuming base_site_url
            if (preg_match('|^/[\\w\\W]+$|', $url)) {
                $url = rtrim($this->base_url, '/') . $url;
            }
            $upload = $this->fetch_remote_file($url, $post);
            if (is_wp_error($upload)) {
                return $upload;
            }
            if ($info = wp_check_filetype($upload['file'])) {
                $post['post_mime_type'] = $info['type'];
            } else {
                return new WP_Error('attachment_processing_error', __('Invalid file type', 'wordpress-importer'));
            }
            $post['guid'] = $upload['url'];
            // as per wp-admin/includes/upload.php
            $post_id = wp_insert_attachment($post, $upload['file']);
            wp_update_attachment_metadata($post_id, wp_generate_attachment_metadata($post_id, $upload['file']));
            // remap resized image URLs, works by stripping the extension and remapping the URL stub.
            if (preg_match('!^image/!', $info['type'])) {
                $parts = pathinfo($url);
                $name = basename($parts['basename'], ".{$parts['extension']}");
                // PATHINFO_FILENAME in PHP 5.2
                $parts_new = pathinfo($upload['url']);
                $name_new = basename($parts_new['basename'], ".{$parts_new['extension']}");
                $this->url_remap[$parts['dirname'] . '/' . $name] = $parts_new['dirname'] . '/' . $name_new;
            }
            return $post_id;
        }

Usage Example

 public function process_attachment($post, $url)
 {
     $post_id = $post["import_id"];
     $xml = simplexml_load_file($this->file);
     $result = $xml->xpath("channel/wg_custom_attachment_url/attachment[post_id='{$post_id}']/custom_url");
     $custom_url = $result != false ? $result[0] : '';
     if ($custom_url != '') {
         $url = THEME_CUSTOM_URI . "/demo/" . $custom_url;
     }
     $return = parent::process_attachment($post, $url);
     return $return;
 }
All Usage Examples Of WP_Import::process_attachment