2016-01-23 38 views
1

我想在我的帖子中爲每個圖片添加div,以便能夠在懸停時添加社交分享圖標。 對於這一點,我已經使用由裏克·桑切斯共享這個有用的代碼:How do I add A Div around each WordPress post image ?如何爲每個WordPress發佈圖像添加div並檢索用於社交分享的徘徊圖像?

function breezer_addDivToImage($content) { 
    // A regular expression of what to look for. 
    $pattern = '/(<img([^>]*)>)/i'; 
    // What to replace it with. $1 refers to the content in the first 'capture group', in parentheses above 
    $the_url = the_permalink(); 
    $replacement = '<div class="imgWrap"> 
         $1 
         <div class="imgDescription"> 
              <div class="theShareLinks"> 
               <img src="http://localhost/mysite/wp-content/uploads/2014/08/dfc2.png" /> 
               <a href="http://twitter.com/share?text=&url='.get_the_permalink() .'" class="img-twitter" title="Share on Twitter" target="_blank"></a> 
               <a href="http://www.facebook.com/sharer.php?u='.get_the_permalink() .'?" class="img-facebook" title="Share on Facebook" target="_blank" onclick="window.open(this.href, \'newwin\', \'width=500, height=200\'); return false;" ></a> 
               <a href="https://plus.google.com/share?url='.get_the_permalink() .'" class="img-google" title="Share on Google" target="_blank"></a> 
              </div> 
             </div> 
        </div>'; 

    // run preg_replace() on the $content 
    $content = preg_replace($pattern, $replacement, $content); 

    // return the processed content 
    return $content; 
} 

add_filter('the_content', 'breezer_addDivToImage'); 

有了這個代碼,我現在可以顯示每個圖像以上份額的圖標(推特,谷歌& Facebook的),但我的問題是共享圖像始終是帖子的第一個圖像,而不是圖像懸停(例如第二個,第三個等)。 您是否知道我如何根據Rick提供的代碼來做到這一點?如何能夠找回懸停的圖像?

非常感謝您的幫助!

回答

0

我已經在上面的代碼上工作過了,現在我可以在匹配表中找到每個圖像的帖子的url。這將允許檢索社交網絡共享按鈕的每個圖像網址,但現在我被阻止瞭如何使用preg_replace替換變量,每個圖像都會有所不同,因爲它將檢索保存在匹配表中的圖像url。你知道我能做到嗎?

對於檢索每個圖像URL我用這個代碼:

// search for images inside content and return images URLs 
    $count = preg_match_all('/<\s*img [^\>]*src\s*=\s*[\""\']?([^\""\'>]*)/i' , $content, $matches); 

    // now all my images url are in $matches[1][x]