2016-06-14 113 views
-1

我想在WordPress中添加圖片文章格式。如果用戶沒有上傳精選圖片,但在圖片中添加了圖片,我想從附件中抓取第一張圖片,並將其顯示爲頂部標題圖片,其餘部分顯示在文章正文中。這是我想出的功能。如果特色圖片上傳,則可以使用,但如果不是,則會抓取甚至不在帖子正文中的圖片。看起來它沒有得到帖子的ID。我做錯了什麼?請幫忙。這裏是我的代碼:WordPress圖片文章和圖庫發佈問題

function justblog_get_attachment(){ 
if(has_post_thumbnail()) { 
    the_post_thumbnail('large', array('class' => 'blog-main-image')); 
} else { 
    // No post thumbnail, try attachments instead. 
    $attachments = get_children(array('post_parent' => $post->ID, 
             'post_type' => 'attachment', 
             'post_mime_type' => 'image', 
             'order' => 'DESC', 
             'orderby' => 'menu_order ID')); 

    foreach($attachments as $att_id => $attachment) { 
     $full_img_url = wp_get_attachment_image_src($attachment->ID, 'full', true); 
    } 
    if ($attachments) { 
     echo '<img src="' . esc_url($full_img_url[0]) . '" alt="Title Image" class="blog-main-image" />'; 
    } 
} 
wp_reset_postdata(); 
} 

回答

0

你需要使用全局填充$郵寄或通過$柱插入函數作爲參數,前者表現出以下

function justblog_get_attachment(){ 
    if(has_post_thumbnail()) { 
     the_post_thumbnail('large', array('class' => 'blog-main-image')); 
    } else { 
     // No post thumbnail, try attachments instead. 
     global $post; 
     $attachments = get_children(array('post_parent' => $post->ID, 
              'post_type' => 'attachment', 
              'post_mime_type' => 'image', 
              'order' => 'DESC', 
              'orderby' => 'menu_order ID')); 

     foreach($attachments as $att_id => $attachment) { 
      $full_img_url = wp_get_attachment_image_src($attachment->ID, 'full', true); 
     } 
     if ($attachments) { 
      echo '<img src="' . esc_url($full_img_url[0]) . '" alt="Title Image" class="blog-main-image" />'; 
     } 
    } 
    wp_reset_postdata(); 
} 

你可以嘗試這種使用CSS和一點點的PHP。基本上你可以修改你的頭文件代碼,在你的頁面上添加一個額外的類到你的body或div wrapper。

if (has_post_thumbnail($post->ID)){?> 

    <div class="post-body no-feat-img"> 

<?php } else { ?> 
    <div class="post-body"> 
<?php } 

然後使用這個類,您可以在發佈內容中定位第一張圖片,使img絕對並將其與頂部對齊。

在此處看到示例https://jsfiddle.net/1pveo2wn/1/ - 圖像下方有一個按鈕用於切換課程。這不是理想的,但它是一種方法。另一種是在輸出之前過濾發佈內容,拉出圖像並顯示爲特色圖像。

我不會爲過濾方法執行代碼的一個原因是,我花了最近2天來繞過srcset和wordpress the_post_thumbnail()來輸出適合每種常見屏幕類型的普通容器大小的不同大小(移動到寬屏)。因此,我認爲你應該放棄這一點,只使用特色圖像,如果用戶未能選擇特色圖像,他們的強硬。

+0

嗨大衛,我試過你的修復,它返回一個空的數組。我正在調用WP Loop中的函數,所以它應該抓取帖子的ID並從那裏加載附件。帖子ID顯示正常!我正在調用WP循環內的模板部分。請有任何想法嗎? –

+0

你需要仔細檢查圖像是如何包含在帖子上。這將更有可能發佈後,而不是後者的子女。 – David

+0

我實際上是WordPress的新手,仍然在學習。我沒有修改WP如何將圖像添加到默認帖子(我沒有在這裏處理自定義帖子)。圖像不應該默認是帖子的子女?我正試圖解決這個問題三天了。當我回顯圖像時,它會加載媒體庫中的所有圖像。出於一些奇怪的原因,'post_parent'設置爲'get_the_ID()/ the_ID/$ post-> ID'並不打擾。我在循環內部,它應該從循環中取出帖子ID並加載來自該特定帖子的圖像,而不是整個庫。請在這裏幫助我。快要瘋了。 –