Last active
February 10, 2023 18:00
-
-
Save Niq1982/dd1292b25864e259bf9f6c5dc4f4e445 to your computer and use it in GitHub Desktop.
Add focal point to WordPress featured image with WP Smart Crop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// This requires the WP Smart Crop plugin | |
// Get the thumbnail ID | |
$thumbnail_id = get_post_thumbnail_id( get_the_ID() ); | |
// Check if the crop is enabled on the thumbnail and get the dimensions | |
$crop_dimensions = get_post_meta( $thumbnail_id, '_wpsmartcrop_enabled', true ) ? get_post_meta( $thumbnail_id, '_wpsmartcrop_image_focus', true ) : []; | |
// Add percentage to dimensions and reverse array (top comes first in array) | |
$parsed_dimensions = array_map( | |
function ( $dimension ) { | |
return $dimension . '%'; | |
}, | |
array_reverse( $crop_dimensions ) | |
); | |
// Set the thumbnail attributes | |
$attrs = [ | |
'style' => $parsed_dimensions ? 'object-position:' . implode( ' ', $parsed_dimensions ) . ';' : '', | |
]; | |
// Do the thumbnail | |
?> | |
<div class="post-thumbnail"> | |
<?php the_post_thumbnail( 'post-thumbnail', $attrs ); ?> | |
</div><!-- .post-thumbnail --> | |
<style> | |
.post-thumbnail img { | |
max-height: 30vh; | |
object-fit: cover; | |
width: 100%; | |
} | |
</style> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment