给图片添加自动超链接

4

我已经创建了一个用于图片的WordPress博客。在发布所有帖子时,我没有使用WordPress编辑器上传图片。相反,我使用FillaZilla上传了这些图片。然后,在WordPress编辑器中,我手动写入了所有帖子中只包含图像标签(如下)并发布。所有帖子都不含文本,只有图像。就像这样:

<img alt="" title="" src=""></img>

现在我想问您的是,我希望所有博客文章中的图像都能自动链接到与图像src相同的地址。我的WordPress博客中有200多篇博客文章,我不想逐一编辑它们。以下是WordPress内容区域的代码:

<div class="post-entry">
                                            <p><img src='http://www.mywebsite.com/wp-content/uploads/2012/04/sun.jpg' title="sun" alt="sun" /></p>

</div>

请问有人能帮我吗?我该如何给图片添加超链接?在我的WordPress主题页面的文章-入口div中有没有可以放置代码的地方?

@chandu-vkm在评论中已经解释了我需要的内容。现在我还有一个问题。当我在img标签之前添加span标签时,@chandu-vkm提到的代码不能让我在img标签之前正确添加span标签。相反,它将占位标签放在p标签外面,如下所示:

<div class="post_div">
<span class="entry"></span>
<p>
<img src='http://www.mywebsite.com/wp-content/uploads/2012/04/sun.jpg' title="Cute Teddy Bear" alt="Cute Teddy Bear" />
</p>
</div>

但是我希望标签放在

标签后面,像这样。

 <div class="post_div">
        <p>
         <span class="entry"></span>
        <img src='http://www.mywebsite.com/wp-content/uploads/2012/04/sun.jpg' title="Cute Teddy Bear" alt="Cute Teddy Bear" />
        </p>
    </div>

有人能帮我解决一下吗?

2个回答

3

你可以使用一些jQuery来实现

<div class="post_div">
    <img src='http://www.mywebsite.com/wp-content/uploads/2012/04/sun.jpg' title="sun" alt="sun" />
</div>

like this

$('.post_div img').each(function(){
$(this).wrap(function() {
  return '<a href="' + $(this).attr('src') + '" />';
})   
});

这里是示例http://jsfiddle.net/a4PYd/


@chandu-ckm 问题已经被编辑过了。我再次需要你的帮助 :) - John Carter
这段文本是单独添加的吗?它有任何包装标签吗? - Sujith Kumar KS
抱歉@Chandu-vkm,我又编辑了我的问题。现在这就是我想要做的事情。请再次查看编辑后的问题。 - John Carter

0

如果您确定所有的文章内容都只包含<img>标签,您可以将以下代码片段添加到您的functions.php文件中:

function hyperlink_all_my_content( $content ) {
    $link = "http://www.somelink.com";
    return "<a href='$link'>$content</a>";
}
add_filter( 'the_content', 'hyperlink_all_my_content' );

请注意,这将链接您所有的内容,甚至包括您的WordPress页面。
编辑:
function hyperlink_all_my_content( $content ) {

    $matches = array();
    $nummatches = preg_match("/src=['|\"](.*)['|\"]/", $content, $matches);
    return "<a href='" . $matches[1] . "'>$content</a>";
}
add_filter( 'the_content', 'hyperlink_all_my_content' );

OP想要成千上万个不同的$link,每个$link都等于各种图像的src。使用add_filter()是一个非常好的主意。 - FelipeAls
我想使用图像src作为超链接。无论如何,感谢您的帮助。Chandu发布的上述方法非常有效 :) - John Carter
我再试一次!嘿。 - Kian Ann

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接