将类添加到WordPress图像锚元素

我需要设置围绕没有标题的post中嵌入的图像的元素的样式,但据我所知,没有办法自动添加类或使用定位内部只是没有使用jQuery或其他东西。

这是他们默认出来的方式:

 Sample Image 

是否有一个简单的wordpress PHP方法,我可以在默认情况下在所有这些元素上设置一个简单的“.img”类?

令人困惑的是,这不是Wordpress中的标准function,很多人抱怨它,但据我所知,没有实际的解决方案。

为了澄清,这应该适用于post中的现有图像,而不仅仅是我未来的post!

简要说明和例子

从数据库中检索post后,只要有一个锚标记内部只有一个图像标记,就会将所有指定的类放入锚标记中。

它适用于一个post中的许多图像标签,以及各种其他奇怪的可能性。 例如,像这样的东西

  

会变成

  

代码(适用于functions.php)

 function add_classes_to_linked_images($html) { $classes = 'media-img'; // can do multiple classes, separate with space $patterns = array(); $replacements = array(); $patterns[0] = '/]*class)([^>]*)>\s*]*)>\s*<\/a>/'; // matches img tag wrapped in anchor tag where anchor tag has no existing classes $replacements[0] = ''; $patterns[1] = '/]*)class="([^"]*)"([^>]*)>\s*]*)>\s*<\/a>/'; // matches img tag wrapped in anchor tag where anchor has existing classes contained in double quotes $replacements[1] = ''; $patterns[2] = '/]*)class=\'([^\']*)\'([^>]*)>\s*]*)>\s*<\/a>/'; // matches img tag wrapped in anchor tag where anchor has existing classes contained in single quotes $replacements[2] = ''; $html = preg_replace($patterns, $replacements, $html); return $html; } add_filter('the_content', 'add_classes_to_linked_images', 100, 1); 

其他说明

  • 在第一个正则表达式模式中, (?![^>]*class)是负前瞻,因此第一个正则表达式替换规则仅影响 ,而不是 。 (阅读更多关于外观的内容 。)
  • 在正则表达式中,我认为[^>]*优于.*[^>]*表示零个或多个不是>字符。 没有[^>]* ,我认为如果在一行或其他奇怪的情况下有多个>字符可能会出现问题。
  • 在正则表达式中,反斜杠后跟一个替换中的数字,如''指的是相应括号内的内容阻止相应的模式。 换句话说, \1表示“放置匹配第一组括号内的东西”。
  • add_filter('the_content', 'add_classes_to_linked_images', 10, 1);行中add_filter('the_content', 'add_classes_to_linked_images', 10, 1); ,第一个参数是用于从数据库获取post内容的filter,第二个参数是我们要使用的函数的名称,第三个参数是filter的优先级(更高的数字稍后执行),以及第四个参数是filter的参数数量。
  • 假设您的锚点和图像组合已经包含您要添加的类,此函数将使其在页面的源代码中显示两次。 (别担心,它最多只会出现两次,不会引起任何问题。请参阅上面的示例。)

如果您能够编辑functions.php文件,则添加此代码。 经过测试和validation:

 /** * Attach a class to linked images' parent anchors * Works for existing content */ function give_linked_images_class($content) { $classes = 'img'; // separate classes by spaces - 'img image-link' // check if there are already a class property assigned to the anchor if ( preg_match('/ 

我的朋友在尝试在他的图像上添加prettyPhoto rel时遇到了同样的问题,有1000个链接。

尝试将其添加到主题中的functions.php文件中。 也请记住,无论有人说什么,都不要编辑核心文件。

这最初是为了在标签中添加rel="prettyPhoto" ,现在尝试并记得将class="newClassHere"改为你的class级。

 add_filter('wp_get_attachment_link', 'rc_add_rel_attribute'); function rc_add_rel_attribute($link) { global $post; return str_replace(' 

把它放在你的functions.php中

 function give_linked_images_class($html, $id, $caption, $title, $align, $url, $size, $alt = '' ){ $classes = 'img'; // separated by spaces, eg 'img image-link' // check if there are already classes assigned to the anchor if ( preg_match('//', $html) ) { $html = preg_replace('/()/', '$1 ' . $classes . '$2', $html); } else { $html = preg_replace('/(/', '$1 class="' . $classes . '" >', $html); } return $html; } add_filter('the_content','give_linked_images_class');