Setting featured image from custom field in wordpress

I have a questions about importing posts in wordpress using csv import. I have mapped the csv like this “post_title” “post_content” “featured_image”etc. All the post were imported but the featured image is not showing.

The featured image url is showing in the custom field only.
My question is,How do I get the featured image to show? as I have hundreds of posts, I can not edit them manually.

Related posts

Leave a Reply

2 comments

  1. I had the same problem – I had custom fields on several posts that contained URLs which I wanted to use for featured images. I knew some of the images were already in my media library, so I made the following functions to add an Bulk Edit-action to the editor window, which looped over the posts and uploaded images where the image wasn’t in the library already, or got the ID of the image already in the library, and then set that as the new featured image for the post.

    It’s a rough code, but it works fine – please back up your site before doing this though.

    function does_file_exists($filename) {
        global $wpdb;
        $data = $wpdb->get_results( "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_value LIKE '%/$filename'" );
        foreach ($data as $ID){
            $ID = $ID->post_id;
            if (get_post_type($ID) == "attachment"){
                return $ID;
            }
        }
        return null;
    }
    
    function upload_image_from_URL($image_url, $post_id){
        // Add Featured Image to Post
        $image_name       = pathinfo($image_url)['basename'];
        $upload_dir       = wp_upload_dir(); // Set upload folder
        $image_data       = file_get_contents($image_url); // Get image data
        $unique_file_name = wp_unique_filename( $upload_dir['path'], $image_name ); // Generate unique name
        $filename         = basename( $unique_file_name ); // Create image file name
    
        // Check folder permission and define file location
        if( wp_mkdir_p( $upload_dir['path'] ) ) {
            $file = $upload_dir['path'] . '/' . $filename;
        } else {
            $file = $upload_dir['basedir'] . '/' . $filename;
        }
    
        // Create the image  file on the server
        file_put_contents( $file, $image_data );
    
        // Check image file type
        $wp_filetype = wp_check_filetype( $filename, null );
    
        // Set attachment data
        $attachment = array(
            'post_mime_type' => $wp_filetype['type'],
            'post_title'     => sanitize_file_name( $filename ),
            'post_content'   => '',
            'post_status'    => 'inherit'
        );
    
        // Create the attachment
        $attach_id = wp_insert_attachment( $attachment, $file, $post_id );
    
        // Include image.php
        require_once(ABSPATH . 'wp-admin/includes/image.php');
    
        // Define attachment metadata
        $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
    
        // Assign metadata to attachment
        wp_update_attachment_metadata( $attach_id, $attach_data );
        return $attach_id;
    }
    
    function set_featured_image($post_id){
        if (wp_is_post_revision($post_id)) return;
        if (has_post_thumbnail($post_id)) return;
    
        $image_url = get_field('FIELD_NAME', $post_id);
    
        if ($image_url){        
            $attachment_ID = does_file_exists(pathinfo($image_url)['basename']);
            $attachment_ID = ($attachment_ID ? $attachment_ID : upload_image_from_URL($image_url, $post_id));
    
            if ($attachment_ID){
                $message = "Setting attachment ". $attachment_ID ." to post ". $post_id;
                error_log($message);
                set_post_thumbnail($post_id, $attachment_ID);
            }
        }
    }
    
    add_filter( 'bulk_actions-edit-post', 'register_bulk_update_featured_image' );
    function register_bulk_update_featured_image($bulk_actions) {
        $bulk_actions['update_featured_image'] = "Get featured image from field";
        return $bulk_actions;
    }
    
    add_filter( 'handle_bulk_actions-edit-post', 'bulk_update_featured_image', 10, 3 );
    function bulk_update_featured_image( $redirect_to, $doaction, $post_ids ) {
        if ( $doaction !== 'update_featured_image' ) {
            return $redirect_to;
        }
        foreach ( $post_ids as $post_id ) {
            // Perform action for each post.
            set_featured_image($post_id);
        }
        $redirect_to = add_query_arg( 'bulk_updated_featured_images', count( $post_ids ), $redirect_to );
        return $redirect_to;
    }
    
    add_action( 'admin_notices', 'my_bulk_action_admin_notice' );
    function my_bulk_action_admin_notice() {
        if ( ! empty( $_REQUEST['bulk_updated_featured_images'] ) ) {
            $id_count = intval( $_REQUEST['bulk_updated_featured_images'] );
            printf('<div id="message" class="updated fade">Updated %s featured images.</div>',
                $id_count);
        }
    }
    
  2. You have to create a new single-post.php template and add the php for the custom field. You can add the new single-post.php template in a child theme so it is not overwritten by theme updates.

    You can use this custom post generator to help you get started. Anything in a child theme is called first. So in your new custom single-Post.php (but call it custom-Post.php or something like that) add the logic (if…then) to render the themes single-post.php.

    Then in your new custom-Post.php add this where you want the image to be displayed:

    **<img src="<?php the_field('advanced_custom_field_name'); ?>" alt=""/>**.

    The custom-Post.php will add the image tag for the html and Advanced Custom Fields will fill in the URL.

    Alternatively, there might be a setting in your theme that allows you to render the Featured Image in the single post display.