首页 > 解决方案 > 根据图像在 wordpress 中的方向向图像添加类

问题描述

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

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

我有两个问题:

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

标签: javascriptphpwordpress

解决方案


  1. 是的,出于用户交互的原因,最好使用 PHP 而不是 JavaScript。后端性能成本可以忽略不计。
  2. 您将在名为wp_get_attachment_image_attributes. 这使您可以在输出图像之前更改类属性。

以下是过滤器的工作方式:

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 );

推荐阅读