Created
June 4, 2024 05:51
-
-
Save sachithrrra/8feb4153c4db3ba4edaac1031f0e4883 to your computer and use it in GitHub Desktop.
Remove Image Links in WordPress
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
////////// 1. Blank link | |
function remove_links_around_images($content) { | |
// Use regex to remove anchor tags around image tags | |
$pattern = '/<a[^>]*>(\s*<img[^>]*>\s*)<\/a>/i'; | |
$replacement = '$1'; // Keep the image tag and remove the anchor tag | |
$content = preg_replace($pattern, $replacement, $content); | |
return $content; | |
} | |
add_filter('the_content', 'remove_links_around_images'); | |
///////// 2. Image link | |
function link_images_to_their_url($content) { | |
// Use regex to add anchor tags around image tags | |
$pattern = '/(<img [^>]+>)/i'; | |
$replacement = '<a href="$1">$1</a>'; | |
// Add link around image | |
preg_match_all($pattern, $content, $matches); | |
foreach ($matches[0] as $img_tag) { | |
// Get the URL of the image | |
preg_match('/src=["\']([^"\']+)["\']/', $img_tag, $src_match); | |
if (isset($src_match[1])) { | |
$img_url = $src_match[1]; | |
$new_img_tag = '<a href="' . $img_url . '">' . $img_tag . '</a>'; | |
$content = str_replace($img_tag, $new_img_tag, $content); | |
} | |
} | |
return $content; | |
} | |
add_filter('the_content', 'link_images_to_their_url'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment