Php Wordpress自定义链接包装媒体库中插入的图像
我没想到这会很困难,但到目前为止,我还没能实现它 我只想在链接标记中添加一个类名,当您使用媒体库将图像插入文章时,该标记会包装img标记 我想把这个Php Wordpress自定义链接包装媒体库中插入的图像,php,wordpress,Php,Wordpress,我没想到这会很困难,但到目前为止,我还没能实现它 我只想在链接标记中添加一个类名,当您使用媒体库将图像插入文章时,该标记会包装img标记 我想把这个 <a href="http://..."><img src="http://..." alt="..." width="780" height="490" class="alignnone size-full wp-image-12" /></a> 进入这个 <a href="http://..." cl
<a href="http://..."><img src="http://..." alt="..." width="780" height="490" class="alignnone size-full wp-image-12" /></a>
进入这个
<a href="http://..." class="fancylink fancybox.ajax"><img src="http://..." alt="..." width="780" height="490" class="alignnone size-full wp-image-12" /></a>
我可以使用jQuery简单地完成这项工作,但我更喜欢使用wordpress过滤器或自定义函数。因此,文章中的输出包括类名。感谢msbodetti,解决方案如下
function add_colorbox_class_to_image_links($html, $attachment_id, $attachment) {
$linkptrn = "/<a[^>]*>/";
$found = preg_match($linkptrn, $html, $a_elem);
// If no link, do nothing
if($found <= 0) return $html;
$a_elem = $a_elem[0];
// Check to see if the link is to an uploaded image
$is_attachment_link = strstr($a_elem, "wp-content/uploads/");
// If link is to external resource, do nothing
if($is_attachment_link === FALSE) return $html;
if(strstr($a_elem, "class=\"") !== FALSE){
// If link already has class defined inject it to attribute
$a_elem_new = str_replace("class=\"", "class=\"fancylink ", $a_elem);
$html = str_replace($a_elem, $a_elem_new, $html);
}else{ // If no class defined, just add class attribute
$html = str_replace("<a ", "<a class=\"fancylink \" data-fancybox-group=\"gallery\" ", $html);
}
return $html;
}
add_filter('image_send_to_editor', 'add_colorbox_class_to_image_links', 10, 3);
试试这个