javascript - 根据图像在 wordpress 中的方向向图像添加类
问题描述
我正在使用 Wordpress 构建网站,并且正在使用我创建的子主题。
我想根据它们的方向为我的所有图像添加一个类。(.portrait 或 .landscape)
我是用 javascript 做的,但我不知道如何用 php 做。(我还不太清楚如何使用过滤器等)
我有两个问题:
1 - 使用 php 而不是 javascript 性能是个好主意吗?
2 - 如果上一个问题的答案是肯定的,那我该怎么做?使用 php,我如何检查所有图像,并根据它们的方向添加相应的类(.portrait 或 .landscape)?
解决方案
- 是的,出于用户交互的原因,最好使用 PHP 而不是 JavaScript。后端性能成本可以忽略不计。
- 您将在名为
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 );
推荐阅读
- hibernate - Hibernate - 映射问题
- postgresql - 由于子表约束,使用 Entity Framework Core HttpPost 向 Postgres 数据库添加数据失败
- c - connect() 的参数无效
- c++ - 在类声明之前使用
- c - 标准 C 函数在第一次调用时速度较慢,如何正确解决这个问题?
- angular - 具有绝对路径的组件 styleUrls
- python - 在 Qt Creator 中使用 QtCharts 和 python
- marklogic - 如何在 MarkLogic 中控制合并支架
- c++ - 为什么 C++20 范围不只提供管道语法?
- legend - 从熊猫的子图中删除单个图例