简体   繁体   English

将类添加到Wordpress图像<a>锚元素</a>

[英]Add class to Wordpress image <a> anchor elements

I need to style the element that goes around images embedded in a post that don't have captions, but as far as I can tell there is no way to automatically add a class to it or target <a> s with an <img> inside only without using jQuery or something. 我需要设置围绕没有标题的帖子中嵌入的图像的元素的样式,但据我所知,没有办法自动添加类或使用<img>定位<a>内部只是没有使用jQuery或其他东西。

This is how they come out by default: 这是他们默认出来的方式:

<a href="sample.jpg"><img class="alignnone size-full wp-image-20" src="sample.jpg" alt="Sample Image" width="1280" height="914"></a>

Is there a simple wordpress PHP method with which I can just set a simple ".img" class on all those elements by default? 是否有一个简单的wordpress PHP方法,我可以在默认情况下在所有这些元素上设置一个简单的“.img”类?

Confused how this is not standard functionality in Wordpress, lots of people complaining about it but no actual solutions as far as I can see. 令人困惑的是,这不是Wordpress中的标准功能,很多人抱怨它,但据我所知,没有实际的解决方案。

To clarify, this should work on existing images in posts, not just on future posts I make! 为了澄清,这应该适用于帖子中的现有图像,而不仅仅是我未来的帖子!

If you have the ability to edit your functions.php file, then add this code. 如果您能够编辑functions.php文件,则添加此代码。 It is tested and proven: 经过测试和验证:

/**
 * 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('/<a.*? class=".*?"><img/', $content) ) {
    // If there is, simply add the class
    $content = preg_replace('/(<a.*? class=".*?)(".*?><img)/', '$1 ' . $classes . '$2', $content);
  } else {
    // If there is not an existing class, create a class property
    $content = preg_replace('/(<a.*?)><img/', '$1 class="' . $classes . '" ><img', $content);
  }
  return $content;
}

add_filter('the_content','give_linked_images_class');

Brief Explanation and Example 简要说明和示例

After retrieving the post from the data base, this will put all of the specified classes into the anchor tag whenever there is an anchor tag with only an image tag inside of it. 从数据库中检索帖子后,只要有一个锚标记内部只有一个图像标记,就会将所有指定的类放入锚标记中。

It works with many image tags in one post, as well as a variety of other weird possibilities. 它适用于一个帖子中的许多图像标签,以及各种其他奇怪的可能性。 For instance, something like this 例如,像这样的东西

<article>
    <a href="an_image.jpg">
        <img src="an_image.jpg">
    </a>
    <a class="media-img" href="another_image.jpg">
        <img src="another_image.jpg">
    </a>
    <p>Text with a <a href="google.com">link</a></p>
    <a class="big gray ugly" href="third_image.jpg">
        <img src="third_image.jpg">
    </a>
    <a foo="bar" class="big" href="fourth_image.jpg">
        <img src="fourth_image.jpg">
    </a>
</article>

will become 会变成

<article>
    <a class="media-img" href="an_image.jpg">
        <img src="an_image.jpg">
    </a>
    <a class="media-img media-img" href="another_image.jpg">
        <img src="another_image.jpg">
    </a>
    <p>Text with a <a href="google.com">link</a></p>
    <a class="media-img big gray ugly" href="third_image.jpg">
        <img src="third_image.jpg">
    </a>
    <a foo="bar" class="media-img big" href="fourth_image.jpg">
        <img src="fourth_image.jpg">
    </a>
</article>


Code (for functions.php) 代码(适用于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] = '/<a(?![^>]*class)([^>]*)>\s*<img([^>]*)>\s*<\/a>/'; // matches img tag wrapped in anchor tag where anchor tag has no existing classes
    $replacements[0] = '<a\1 class="' . $classes . '"><img\2></a>';

    $patterns[1] = '/<a([^>]*)class="([^"]*)"([^>]*)>\s*<img([^>]*)>\s*<\/a>/'; // matches img tag wrapped in anchor tag where anchor has existing classes contained in double quotes
    $replacements[1] = '<a\1class="' . $classes . ' \2"\3><img\4></a>';

    $patterns[2] = '/<a([^>]*)class=\'([^\']*)\'([^>]*)>\s*<img([^>]*)>\s*<\/a>/'; // matches img tag wrapped in anchor tag where anchor has existing classes contained in single quotes
    $replacements[2] = '<a\1class="' . $classes . ' \2"\3><img\4></a>';

    $html = preg_replace($patterns, $replacements, $html);

    return $html;
}

add_filter('the_content', 'add_classes_to_linked_images', 100, 1);


Other Notes 其他说明

  • In the first regular expression pattern, (?![^>]*class) is a negative lookahead so that the first regex replace rule only affects <a href...><img></a> , not <a class... href...><img></a> . 在第一个正则表达式模式中, (?![^>]*class)是负前瞻,因此第一个正则表达式替换规则仅影响<a href...><img></a> ,而不是<a class... href...><img></a> (Read more on lookarounds .) (阅读更多关于外观的内容 。)
  • In regular expressions for this, I think [^>]* is better than .* . 在正则表达式中,我认为[^>]*优于.* [^>]* means zero or more characters that are not a > . [^>]*表示零个或多个不是>字符。 Without [^>]* , I think there could be problems if there are multiple > characters on one line or in other weird situations. 如果没有[^>]* ,我认为如果在一行或其他奇怪的情况下有多个>字符可能会出现问题。
  • In the regular expressions, the backslash followed by a number in the replacements such as in '<a\\1 class="' . $classes . '"><img\\3></a>' refers to the stuff inside corresponding parenthetical block in the corresponding pattern. 在正则表达式中,反斜杠后跟一个替换中的数字,如'<a\\1 class="' . $classes . '"><img\\3></a>'指的是相应括号内的内容阻止相应的模式。 In other words, \\1 means "put the stuff that matches what's inside the first set of parentheses". 换句话说, \\1表示“放置匹配第一组括号内的东西”。
  • In the line add_filter('the_content', 'add_classes_to_linked_images', 10, 1); add_filter('the_content', 'add_classes_to_linked_images', 10, 1);行中add_filter('the_content', 'add_classes_to_linked_images', 10, 1); , the first parameter is the filter for getting the content of a post from the database, the second parameter is the name of the function we want to use, the third parameter is the priority of the filter (higher numbers are executed later), and the fourth parameter is the number of arguments for the filter. ,第一个参数是用于从数据库获取帖子内容的过滤器,第二个参数是我们要使用的函数的名称,第三个参数是过滤器的优先级(更高的数字稍后执行),以及第四个参数是过滤器的参数数量。
  • Assuming your anchor and image combination already has the class you want to add, this function will cause it to show up twice in the source code of your page. 假设您的锚点和图像组合已经包含您要添加的类,此函数将使其在页面的源代码中显示两次。 (Don't worry, it will only show up twice at most and it won't cause any issues. See example above.) (别担心,它最多只出现两次,不会引起任何问题。请参见上面的例子。)

Just put this in your functions.php 把它放在你的functions.php中

function give_linked_images_class($html, $id, $caption, $title, $align, $url, $size, $alt = '' ){
  $classes = 'img'; // separated by spaces, e.g. 'img image-link'

  // check if there are already classes assigned to the anchor
  if ( preg_match('/<a.*? class=".*?">/', $html) ) {
    $html = preg_replace('/(<a.*? class=".*?)(".*?>)/', '$1 ' . $classes . '$2', $html);
  } else {
    $html = preg_replace('/(<a.*?)>/', '$1 class="' . $classes . '" >', $html);
  }
  return $html;
}
add_filter('the_content','give_linked_images_class');

My friend had the same problem when trying to add prettyPhoto rel's on his image, there are 1000's of links for this. 我的朋友在尝试在他的图像上添加prettyPhoto rel时遇到了同样的问题,有1000个链接。

Try adding this into your functions.php file within your theme. 尝试将其添加到主题中的functions.php文件中。 Please also remember NEVER to edit the core files, no matter what anyone says. 请记住,无论有人说什么,都不要编辑核心文件。

This was originally for adding rel="prettyPhoto" within the <a> tags, try it now and remember to change class="newClassHere" to your class. 这最初是为了在<a>标签中添加rel="prettyPhoto" ,现在试试并记得将class="newClassHere"改为你的班级。

add_filter('wp_get_attachment_link', 'rc_add_rel_attribute');
function rc_add_rel_attribute($link) {
    global $post;
    return str_replace('<a href', '<a class="newClassHere" href', $link);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM