2013-05-08 70 views
0

我有一个老的WordPress网站。当时特色图片并不常见。所以我写了缩略图的自定义代码。Wp从发布的图片设置发布缩略图

现在我改变了我的主题,更新WordPress和精选图片是新主题的标准。

我想设置为该帖子上传的拳头(或任何)图片作为该帖子的精选图片。

我该怎么做?

谢谢。

我想通了

function autoset_featured() { 
     global $post; 
     $already_has_thumb = has_post_thumbnail($post->ID); 
      if (!$already_has_thumb) { 
      $attached_image = get_children("post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1"); 
         if ($attached_image) { 
          foreach ($attached_image as $attachment_id => $attachment) { 
          set_post_thumbnail($post->ID, $attachment_id); 
          } 
         } 
        } 
    } //end function 
add_action('the_post', 'autoset_featured'); 
add_action('save_post', 'autoset_featured'); 
add_action('draft_to_publish', 'autoset_featured'); 
add_action('new_to_publish', 'autoset_featured'); 
add_action('pending_to_publish', 'autoset_featured'); 
add_action('future_to_publish', 'autoset_featured'); 

,这是为我工作。

回答

1

试试这个:

$args = array(
      'post_type'  => 'posts', 
      'numberposts' => -1, 
     ); 
    $posts = get_posts($args); 
    foreach($posts as $post_temp){ 
     $args = array(
      'post_type'  => 'attachment', 
      'numberposts' => 1, 
      'post_parent' => $post_temp->id, 
      'orderby'  => 'post_date', 
      'order'   => 'DESC' 
     ); 
     $attachment = get_posts($args); 

     set_post_thumbnail($post_temp->id, $attachment->id); 
    }