2015-09-22 93 views
0

所以,我下面以在WordPress後添加圖像:圖片上傳到WordPress

<?php 
    global $current_user; 

    if('POST' == $_SERVER['REQUEST_METHOD'] && !empty($_POST['action'])) { 
    if (isset ($_POST['title'])) { 
      $title = $_POST['title']; 
       } else { 
        echo 'Please enter a title'; 
       } 
      if (isset ($_POST['description'])) { 
       $description = $_POST['description']; 
       } else { 
        echo 'Please enter the content'; 
       } 
      $tags = $_POST['post_tags']; 
      $custom_field_1 = $_POST['custom_1']; 
      $custom_field_2 = $_POST['custom_2']; 
      $post = array(
        'post_title' => $title, 
        'post_content' => $description, 
        'post_category' => $_POST['cat'], 
        'tags_input' => $tags,         
        'post_status' => 'publish',   
        'post_type' => $_POST['post_type'] 
       ); 

        $pid = wp_insert_post($post); 
        add_post_meta($pid, 'rh_content', $custom_field_1, true); 
          add_post_meta($pid, 'rh_item', $custom_field_2, true); 

      if ($_FILES) { 
        foreach ($_FILES as $file => $array) { 
        $newupload = insert_attachment($file,$pid); 
                 } 
          }        
          wp_redirect(home_url());          
         }       
         do_action('wp_insert_post', 'wp_insert_post'); 
        ?> 

所以,它允許要被上傳的圖像可以由get_the_post_thumbnail顯示。

<?php if (has_post_thumbnail()) { ?> 
    <div class="rhmi_thumb">       
     <?php if (has_post_thumbnail($loop->post->ID)) echo get_the_post_thumbnail($loop->post->ID, 'rh_site') ?> 
    </div> 
<?php } ?> 

不過,即使沒有圖像上傳(即沒有縮略圖),它仍然顯示class="rhmi_thumb"。所以,我在猜測是否上傳圖片,帖子認爲有縮略圖。

應該在帖子上傳表單中進行哪些修改?

感謝

回答

1

對於上傳圖像到頁/後你必須使用wp_insert_attachment()。我已經從那裏添加了WordPress的網站鏈接,你可以得到如何實現這一點的例子。謝謝!