DaFois
DaFois

Reputation: 2223

Wordpress - Featured image attached but not showing in post editor


I have a custom post type named 'portfolio' and I set featured image using a script that takes a snapshot of some website I want to be updated daily using the service at wordpress.org

http://s.wordpress.com/mshots/v1/' . urlencode($site) . '?w=' . $width;

After the script runs I find the images in the media library and they seem to be attached to the post, but if I check the post there isn't any featured image and the image also doesn't show up in the front end. I post here the script I'm using, and I hope someone can help me.

<?php
function ss_screenshot_action($post_id){
  $width = 612;
  $site = trim(get_post_meta($post_id, 'site_url', true));

  if ($site != ''){
      $query_url =  'http://s.wordpress.com/mshots/v1/' . urlencode($site) . '?w=' . $width;

      $imagename= str_replace('%2F','',str_replace('.','-', substr(substr(basename($query_url), 13), 0, -6))). '.jpg';
      $save_path = ABSPATH.'wp-content/uploads/site_snapshots/';
      $save_img_path = ABSPATH.'wp-content/uploads/site_snapshots/'.$imagename;

      // first time, the image doesn't exist
      if(!file_exists($save_img_path)) { 
          $image = getimg($query_url);
          file_put_contents($save_img_path, $image);
          //is the image bigger than 10KB? (cicle and wait for the image to be generated)
          while (filesize($save_img_path) < 10000) {
              unlink($save_img_path);
              sleep(1);
              $image = getimg($query_url);
              file_put_contents($save_img_path, $image);
          }
          //insert the attachment
          saveSiteImg($save_img_path);
      }

      //if the image exist and it is older than a day, take it again and change only the image for the attachment - 1day = 86400 = 24*3600 seconds
      if(file_exists($save_img_path) && get_post_thumbnail_id($post_id) != 0  && (time() - filemtime($save_img_path)) > 86400) {         
          $image = getimg($query_url);
          file_put_contents($save_img_path, $image);
          while (filesize($save_img_path) < 10000) {
              unlink($save_img_path);
              sleep(1);
              $image = getimg($query_url);
              file_put_contents($save_img_path, $image);
          }
          //maybe here I have to update the metadata for the attachment and to regenerate the thumbnails
      }
   } 
}
add_action( 'save_post', 'ss_screenshot_action' );

function getimg($url) {         
    $headers[] = 'Accept: image/jpeg';              
    $headers[] = 'Connection: Keep-Alive';         
    $headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';         
    $user_agent = 'php';         
    $process = curl_init($url);         
    curl_setopt($process, CURLOPT_HTTPHEADER, $headers);         
    curl_setopt($process, CURLOPT_HEADER, 0);  
    //Required for http(s)
    curl_setopt($process, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($process, CURLOPT_SSL_VERIFYPEER, false);
    //
    curl_setopt($process, CURLOPT_USERAGENT, $user_agent);         
    //curl_setopt($process, CURLOPT_TIMEOUT, 30);         
    curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);         
    curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);  
    curl_setopt($process, CURLOPT_BINARYTRANSFER,1);
    $return = curl_exec($process);         
    curl_close($process);         
    return $return;     
}

function saveSiteImg($filename) {
    // $filename should be the path to a file in the upload directory.
    global $post;
    // The ID of the post this attachment is for.
    $parent_post_id = $post->ID;

    // Check the type of file. We'll use this as the 'post_mime_type'.
    $filetype = wp_check_filetype( basename( $filename ), null );

    // Get the path to the upload directory.
    $wp_upload_dir = wp_upload_dir();

    // Prepare an array of post data for the attachment.
    $attachment = array(
        'guid'           => $wp_upload_dir['url'] . '/' . basename( $filename ), 
        'post_mime_type' => $filetype['type'],
        'post_title'     => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
        'post_content'   => '',
        'post_status'    => 'inherit'
    );

    // Insert the attachment.
    $attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );

    // Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
    require_once( ABSPATH . 'wp-admin/includes/image.php' );

    // Generate the metadata for the attachment, and update the database record.
    $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
    wp_update_attachment_metadata( $attach_id, $attach_data );

    set_post_thumbnail( $parent_post_id, $attach_id );
}

EDIT 1 The following is where I declare the custom post type:

function create_portfolio() {
    $labels = array(
        'name'               => __('Portfolio' , 'portfolio-plugin'),
        'singular_name'      => __('Portfolio' , 'portfolio-plugin'),
        'add_new'            => __('Aggiungi testata', 'portfolio-plugin'),
        'add_new_item'       => __('Aggiungi nuova testata' , 'portfolio-plugin'),
        'edit_item'          => __('Modifica testata', 'portfolio-plugin'),
        'new_item'           => __('Nuova testata', 'portfolio-plugin'),
        'all_items'          => __('Tutte le testate', 'portfolio-plugin'),
        'view_item'          => __('Vedi le testate' , 'portfolio-plugin'),
        'search_items'       => __('Cerca testata' , 'portfolio-plugin'),
        'not_found'          => __('Nessuna testata inserita', 'portfolio-plugin'),
        'not_found_in_trash' => __('Work Not found in the trash', 'portfolio-plugin'),
    );

    $args = array(
        'labels'             => $labels,
        'public'             => true,
        'rewrite'            => array('slug' => 'portfolio'),
        'has_archive'        => true,
        'hierarchical'       => true,
        'menu_position'      => 22,
        'menu_icon'          => 'dashicons-welcome-write-blog',
        'supports'           => array(
                                'title',
                                'editor',
                                'thumbnail',
                                'excerpt',
                                'page-attributes' 
                                ),

    );

   register_post_type('portfolio', $args);
}

Upvotes: 0

Views: 1085

Answers (1)

Peter
Peter

Reputation: 741

Use the register_post_type supports parameter:

'supports' => array( 'thumbnail' )

https://codex.wordpress.org/Function_Reference/register_post_type

register_post_type( $post_type, $args );

Upvotes: 0

Related Questions