skip to Main Content

I have some code which is programmatically creating a post using wp_insert_post.

Within the code I am setting the featured image using:

$image = "https://XXXX.com/content/uploads/2023/08/002-2.jpg";

(Note: ignore the XXXX. This URL will also be dynamic in future and will require the full https//… url path, so removing it is not an option).

When the media is saved to wordpress using wp_insert_attachment, the URL to the file duplicates the site url, for example:

https://XXXX.com/content/uploads/https://XXXX.com/content/uploads/2023/08/002-2.jpg

I am unable to find out why this is happening? My code is below, any help would be much appreciated!

PHP:

// Create Post Content
    $wpdb->query( $query );
    if ( !$wpdb->num_rows ) {
        $post_id = wp_insert_post(
            array(
                'author'   => $current_user_id,
                'post_title'    => 'test',
                'post_content'  => 'test content...',
                'post_status'   => 'draft',
                'post_type'     => 'post'
            )
        );
        
        $image = "https://********.com/content/uploads/2023/08/002-2.jpg";
        
        $attachment_file_type = wp_check_filetype(basename($image), null);
        
        $wp_upload_dir = wp_upload_dir();
        
        $attachment_args = array(
            'guid'           => $wp_upload_dir['url'] . '/' . basename($image),
            'post_title'     => preg_replace('/.[^.]+$/', '', basename($image)),
            'post_mime_type' => $attachment_file_type['type']
        );
        
        $attachment_id = wp_insert_attachment($attachment_args, $image, $post_id);

        require_once(ABSPATH . 'wp-admin/includes/image.php');

        $attachment_meta_data = wp_generate_attachment_metadata($attachment_id, $image);

        wp_update_attachment_metadata($attachment_id, $attachment_meta_data);

        set_post_thumbnail($post_id, $attachment_id);
        
    }

2

Answers


  1. I checked your code. It works fine. Might be on your site exist some filters for the hooks: wp_generate_attachment_metadata or wp_update_attachment_metadata

    Perhaps a function hangs on them in one of the plugins or in your site template. You can try setting the default template or disabling plugins and see if the problem persists.

    Also, I recommend debugging what happened and where is coming to the wrong path:

    // Create Post Content
        $wpdb->query( $query );
        if ( !$wpdb->num_rows ) {
            $post_id = wp_insert_post(
                array(
                    'author'   => $current_user_id,
                    'post_title'    => 'test',
                    'post_content'  => 'test content...',
                    'post_status'   => 'draft',
                    'post_type'     => 'post'
                )
            );
        
            $image = "https://********.com/content/uploads/2023/08/002-2.jpg";
        
            $attachment_file_type = wp_check_filetype(basename($image), null);
        
            $wp_upload_dir = wp_upload_dir();
        
            echo '<b>wp_upload_dir:</b> ';
            echo '<pre>' . print_r( $wp_upload_dir, 1 ) . '</pre><br />';
        
            $attachment_args = array(
                'guid'           => $wp_upload_dir['url'] . '/' . basename($image),
                'post_title'     => preg_replace('/.[^.]+$/', '', basename($image)),
                'post_mime_type' => $attachment_file_type['type']
            );
        
            $attachment_id = wp_insert_attachment($attachment_args, $image, $post_id);
        
            require_once(ABSPATH . 'wp-admin/includes/image.php');
        
            $attachment_meta_data = wp_generate_attachment_metadata($attachment_id, $image);
            echo '<b>wp_generate_attachment_metadata:</b> ';
            echo '<pre>' . print_r( $attachment_meta_data, 1 ) . '</pre><br />';
        
            wp_update_attachment_metadata($attachment_id, $attachment_meta_data);
        
            echo '<b>wp_update_attachment_metadata:</b> ';
            echo '<pre>' . print_r( wp_get_attachment_metadata($attachment_id), 1 ) . '</pre><br />';
        
            set_post_thumbnail($post_id, $attachment_id);
        
        }
    

    Then you can understand where the problem appears and fix it.

    Login or Signup to reply.
  2. You follow this code. Hope your problem will be solved.

       global $wpdb, $current_user;
        
        $query = "YOUR_QUERY_HERE"; // Replace with your actual query
        
        $result = $wpdb->get_results($query); // Assuming you expect multiple rows
        
        if (empty($result)) {
            // Post does not exist, create a new post
            $current_user_id = $current_user->ID;
        
            $post_title = 'test';
            $post_content = 'test content...';
        
            // Create a new draft post
            $post_id = wp_insert_post(
                array(
                    'post_author'   => $current_user_id,
                    'post_title'    => $post_title,
                    'post_content'  => $post_content,
                    'post_status'   => 'draft',
                    'post_type'     => 'post'
                )
            );
        
            $image = "https://********.com/content/uploads/2023/08/002-2.jpg";
        
            // Download the image to your server
            $image_tmp = download_url($image);
            $image_name = basename($image);
            $image_type = wp_check_filetype($image_name, null);
            $image_title = preg_replace('/.[^.]+$/', '', $image_name);
            $uploads = wp_upload_dir();
            $upload_path = $uploads['url'];
            // Prepare the image data to insert as an attachment
            $attachment = array(
                'guid'           => $upload_path . '/' . $image_name,
                'post_mime_type' => $image_type['type'],
                'post_title'     => $image_title,
                'post_content'   => '',
                'post_status'    => 'inherit'
            );
        
            // Insert the attachment into the media library
            $attachment_id = wp_insert_attachment($attachment, $image_tmp, $post_id);
        
            // Include image.php for processing the image
            require_once(ABSPATH . 'wp-admin/includes/image.php');
        
            // Generate and save attachment metadata
            $attachment_data = wp_generate_attachment_metadata($attachment_id, $image_tmp);
            wp_update_attachment_metadata($attachment_id, $attachment_data);
        
            // Set the image as the post's featured image (post thumbnail)
            set_post_thumbnail($post_id, $attachment_id);
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search