下载帮

您现在的位置是:首页 > CMS教程 > WordPress

WordPress

WordPress批量去掉文章图片的链接

2020-03-16 06:38WordPress

wordpress在发布文章的时候,插入图片,有个默认的选项是“链接到媒体页面”,如果不改成“无”的后果就是点击文章的图片时会在当前窗口跳转到图片页面,不仅用户体验不好,而且造成搜索引擎蜘蛛爬去无法返回的不良后果,发现这个问题后,余斗及时找到解决方法,如下:

一、将以下代码复制到当前使用主题的functions.php文件中:


	/* 去文章图片链接*/
add_filter( 'the_content','a_blank');
function a_blank($c) {
global $post;
$s = array('/href="(.+?.(jpg|bmp|png|jepg|gif))"/i'=>'');
foreach($s as$p => $r){
$c = preg_replace($p,$r,$c);
}
return$c;
}

这样就可以实现以后生成的文章图片和已经发布的文章中的图片都会默认无链接,唯一瑕疵就是还会有a标签,但是是空标签,这没什么影响,强迫症可以用下面一个方法完美解决。

二、将以下代码复制到当前使用主题的functions.php文件中(此方法对已发布文章不生效):


	/* 去文章图片链接*/
update_option('image_default_link_type', 'none');


	/* 去文章图片链接*/
function wpc_imagelink_setup() {
$image_set = get_option( 'image_default_link_type' );
if ($image_set !== 'none') {
update_option('image_default_link_type', 'none');
}
}
add_action('admin_init', 'wpc_imagelink_setup', 10);


扩展:

有的用户可能会需要文章中的图片链接在新窗口打开,将以下代码复制到当前使用主题的functions.php文件中:


	/* 文章图片链接新窗口打开*/
add_filter( 'the_content','a_blank');
function a_blank($c) {
global $post;
$s = array('/href="(.+?.(jpg|bmp|png|jepg|gif))"/i'=>'href="$1"
target="_blank"');
foreach($s as$p => $r){
$c = preg_replace($p,$r,$c);
}
return$c;
}

有的则需要将没有链接的图片加上链接,这个分两种情况:

一是链接为文章地址(同时添加alt与title属性为文章标题),将以下代码复制到当前使用主题的functions.php文件中:


	/* 图片自动链接到文章,添加标题和ALT属性 */
function auto_post_link($content) {
    global $post;
                $content = preg_replace('/<\s*img\s+[^>]*?src\s*=\s*(\'|\")(.*?)\\1[^>]*?\/?\s*>/i', "<a href=\"".get_permalink()."\" title=\"".$post->post_title."\" ><img src=\"$2\" alt=\"".$post->post_title."\"/></a>", $content);
    return $content;
}
add_filter ('the_content', 'auto_post_link',0);

如果文章图片较多,第一张图片添加为文章链接,剩下的则只加alt与title属性:


	/*--------------------------------------
自动为第一张图片添加链接地址,其他图片只加alt属性,不加链接
默认链接地址为当前文章的链接,alt属性为当前文章的标题
通过修改判断语句if($count==1),可以为指定顺序图片添加链接,不局限于第一个图片
--------------------------------------*/

$count = 0;
function auto_image_handler($matches){
    global $count,$post;
    $count++;
    if($count==1){//第一个图片添加链接地址
        return "<a href=\"".get_permalink()."\" title=\"".$post->post_title."\" ><img src=\"$matches[2]\" alt=\"".$post->post_title."\"/></a>";
    }
    else{//其他图片添加alt属性
        return "<img src=\"$matches[2]\" alt=\"".$post->post_title."\"/></a>";
    }
}
function auto_post_link($content){
    $content = preg_replace_callback('/<\s*img\s+[^>]*?src\s*=\s*(\'|\")(.*?)\\1[^>]*?\/?\s*>/i',
    'auto_image_handler',$content);
    return $content;
}
add_filter ('the_content', 'auto_post_link',0);

这里需要注意的是,使用上面的代码后,由于替代了图片的多余属性,将导致图片的对齐方式失效,大家自行取舍使用;

二是文章图片本没有链接,想加上图片文件的链接,将以下代码复制到当前使用主题的functions.php文件中:


	//图片默认连接到媒体文件(原始链接)
update_option('image_default_link_type', 'file');

文章评论