【问题标题】:Adding a class to images depending on their orientation in wordpress根据图像在 wordpress 中的方向向图像添加类
【发布时间】:2020-04-21 18:53:02
【问题描述】:

我正在使用 Wordpress 构建网站,并且正在使用我创建的子主题。

我想根据图像的方向为我的所有图像添加一个类。 (.portrait 或 .landscape)
我是用 javascript 做的,但我不知道如何用 php 做。 (我还不太清楚如何使用过滤器等)

我有两个问题:

1 - 在性能方面使用 php 而不是 javascript 是个好主意吗?
2 - 如果上一个问题的答案是肯定的,那我该怎么做?使用 php,如何检查所有图像并根据它们的方向添加相应的类(.portrait 或 .landscape)?

【问题讨论】:

  • 您使用什么 WordPress 功能插入图片? wp_get_attachment_image()?
  • 现在我只需要它用于特色图像,所以我使用 the_post_thumbnail() 或 get_the_post_thumbnail()。但它也可能对其他类型有用,所以 wp_get_attachment_image() 也可能有用。

标签: javascript php wordpress


【解决方案1】:
  1. 是的,出于用户交互的原因,最好使用 PHP 而不是 JavaScript。后端性能成本可以忽略不计。
  2. 您可以在wp_get_attachment_image function 中使用名为wp_get_attachment_image_attributes 的WordPress 过滤器。这使您可以在输出图像之前更改类属性。

过滤器的工作原理如下:

function add_orientation_class( $attr, $attachment ) {

    $metadata = get_post_meta( $attachment->ID, '_wp_attachment_metadata', true);

    // Sanity check: we need both width and height to add the orientation class. If either are missing, we should return the attributes.
    if ( empty($metadata['width']) || empty($metadata['height'])) {
        return $attr;
    }

    // Sanity check x2: class should be set by now, but another filter could have cleared it out.
    if ( !isset($metadata['class'])) {
        $metadata['class'] = '';
    }

    if ( $metadata['width'] > $metadata['height'] ) { // If width is greater than height, the image is a landscape image.
        $attr['class'] .= ' landscape';
    } else { // If not, it's a portrait image.
        $attr['class'] .= ' portrait';
    }

    // Return the attributes.
    return $attr;
}

add_filter( 'wp_get_attachment_image_attributes', 'add_orientation_class', 10, 2 );

【讨论】:

    猜你喜欢
    • 2020-12-11
    • 1970-01-01
    • 1970-01-01
    • 2012-02-17
    • 2011-11-26
    • 2012-02-26
    • 2011-01-05
    • 1970-01-01
    • 2012-12-16
    相关资源
    最近更新 更多