在类别档案中,我使用the_content read more来显示带有文本的图像。我想将此图片链接到帖子。我在制作它时遇到了问题,因为我在帖子中的第一张图片已经链接到外部网站,或者它们不是。
我知道有两种方法可以做到这一点 1.我从the_content中删除第一张图片,然后使用the_post_thumbnail()。
function remove_first_image ($content) {
$content = preg_replace("/<img[^>]\>/i", "", $content, 1);
} return $content;
add_filter('the_content', 'remove_first_image');
有效。但它只剥离图像。我有很多帖子也是链接。如何更改此代码,以便删除第一个带有链接的图像(如果已存在)?我尝试添加它。
$content = preg_replace("/<a href[^>]\>/i", "", $content, 1);
但它还不够好。它确实剥离链接。但是如果图像没有链接,它会剥离下一个链接。这通常是the_content更多的链接。我尝试在一个preg_replace中混合使用href和img,但不能使它工作。
第二个选项只是更改/添加href到图像。我找到了这段代码。
$content = preg_replace("/<img[^>]+\>/i","", $content, 1);<br>
$old = '/(<img[^>]+\/>)/i';<br>
$new = '<a href="'.esc_url(get_permalink()).'" title="'.esc_attr(get_the_title()).'">$1</a>';<br>
$content = preg_replace($old, $new, $content, 1);
这个也很好。但是和以前的方法有同样的问题。因为我的图像都是href而没有。
你可以帮我解决这个问题吗?还有哪种方法可以更好地使用。那是更轻量级的。答案 0 :(得分:0)
我设法让它发挥作用。不确定这是否是正确的方法。 这是代码。
if (!function_exists('image_to_post')) {
function image_to_post($content){
if (!is_singular()) {
$content = preg_replace(array('{<a[^>]*><img}','{/></a>}'), array('<img','/>'), $content);
$old = '/(<img[^>]+\/>)/i';
$new = '<a href="'.esc_url(get_permalink()).'" title="'.esc_attr(get_the_title()).'">$1</a>';
$content = preg_replace($old, $new, $content, 1);
}
return $content;}
add_filter('the_content', 'image_to_post');}