为WordPress[gallery]短标签里的图片链接添加更多属性

Add rel Attribute to Image Links in WordPress Galleries

add-filter-gallery

如果你想给[ gallery ] 里的图片链接加上而外的属性, rel 或者 class 等等,去配合使用 fancybox、 lightbox 等 jQuery 插件。代码如下:

If you want to use either Fancybox or Lightbox scripts for image galleries, you need to add the rel attribute to all full size image links. Here is how to do it:

add_filter('wp_get_attachment_link', 'add_gallery_id_rel');
function add_gallery_id_rel($link) {
	global $post;
	return str_replace('<a href', '<a class="fancybox" rel="gallery-'. $post->ID .'" href', $link);
}

我们简单的吧 <a href 替换成 <a class=”fancybox” rel=”gallery-n” href, n 是独立的 post ID

We simply replace <a href with <a rel="gallery-n" href where n is a unique post ID. This filter is applied in /wp-includes/post-template.php.

如果想在图片链接里加入一个 caption (可以在图片弹出时代替title 显示在图片下方) 属性,里面显示下载该图片,可以使用下面的方法:

add_filter('wp_get_attachment_link', 'add_gallery_id_rel');
function add_gallery_id_rel($link ) {
    global $post;
	//$link = preg_replace("/title=\'(.*?)\'/",'',$link);
	preg_match("/href=\'(.*?)\'/", $link, $matches);
	$img_url = $matches[1];
	$caption = '';
	if(!empty($img_url))
		$caption = esc_attr('<a href="'.$img_url.'" target="_blank">'.__('Download',ESSCA_TEXTDOMAIN).'</a>');
    return str_replace('<a href', '<a class="fancybox" caption="'.$caption.'" rel="gallery-'. $post->ID .'" href', $link);
}

Comments

330 responses to “为WordPress[gallery]短标签里的图片链接添加更多属性”