Skip to content

Instantly share code, notes, and snippets.

@Niq1982
Last active February 10, 2023 18:00
Show Gist options
  • Save Niq1982/dd1292b25864e259bf9f6c5dc4f4e445 to your computer and use it in GitHub Desktop.
Save Niq1982/dd1292b25864e259bf9f6c5dc4f4e445 to your computer and use it in GitHub Desktop.
Add focal point to WordPress featured image with WP Smart Crop
<?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