I’m building a website with WordPress and I’m using a child theme I created.
I would like to add a class to all my images depending on their orientation. (.portrait or .landscape)
I did it with javascript but I have no idea how to do it with php.
(I don’t know very well yet how to use filters and so)
I have 2 questions:
1 – Is it a good idea to do it with php instead of javascript performance-wise ?
2 – If the answer to the previous question is yes, then how can I do that? Using php, how can I check all the images and, depending on their orientation, add the corresponding class (.portrait or .landscape) ?
Advertisement
Answer
- Yes, it’s better to do it with PHP rather than JavaScript, for user interaction reasons. The back-end performance cost is negligible.
- You’d use a WordPress filter inside of the wp_get_attachment_image function called
wp_get_attachment_image_attributes
. This lets you change the class attribute before the image is output.
Here’s how the filter would work:
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 );