【问题标题】:How do I add div around each WordPress post images & retrieve hovered image for social sharing?如何在每个 WordPress 帖子图像周围添加 div 并检索悬停图像以进行社交共享?
【发布时间】:2016-04-30 03:31:41
【问题描述】:

我想在帖子中的每个图像周围添加 div,以便能够在悬停时添加社交分享图标。 为此,我使用了 Rick Sanchez 分享的这个有用代码:How do I add A Div around each WordPress post image ?

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' );

使用此代码,我现在可以在每张图片(twitter、google 和 facebook)上方显示共享图标,但我的问题是共享的图片始终是帖子的第一张图片,而不是悬停的图片(例如第二,第三等等)。 你知道我如何根据 Rick 提供的代码来做到这一点吗?如何检索悬停的图像?

非常感谢您的帮助!

【问题讨论】:

    标签: php wordpress image hover share


    【解决方案1】:

    我已经处理了上面的代码,现在我可以在匹配表中检索帖子中每个图像的 url。这将允许检索社交网络共享按钮的每个图像 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]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-08
      • 2013-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多