ACF relationship thumbnail size and aspect ratio

Advanced Custom Fields is an essential part of my customized WordPress backend. One of its great features is the relationship field to connect one post to another.

For example to feature pages, posts or products on a different page. In my current situation I want to display some featured WooCommerce products. Normally the type of content doesn’t make any difference to the field, but displaying wine bottle in a square thumb, looks quite strange.

acf-relationship-square-thumbs

Filtering the ACF relationship results

ACF has a filter for the relationship results. I’ll use this filter to replace the thumbnail with a regular expression.

I defined a custom image size “acf-thumb”.

add_image_size( 'acf-thumb', 21, 21, true );
function acf_relationship_thumbnails($title, $post, $field, $the_post){
 if( in_array('featured_image', $field['result_elements']) ) {
       $image = '';
      if( $post->post_type == 'attachment' ) {
           $image = wp_get_attachment_image( $post->ID, 'acf-thumb' );
        } else {
            $image = get_the_post_thumbnail( $post->ID, 'acf-thumb' );
     }
       $title = preg_replace("/(.*\<div class=\"result-thumbnail\"\>)(.*)(\<\/div\>.*)/", "$1$image$3", $title);
  }
   return $title;
}
add_filter('acf/fields/relationship/result', 'acf_relationship_thumbnails', 10, 4);

Just add the code to functins.php of your theme and regenerate your thumbnails.

acf-relationship

 

One Response to “ACF relationship thumbnail size and aspect ratio”

  1. Johnathan Christopher

    For anyone trying to do that in 2019, ACF changed some field names for their filters:

    instead of:
    function acf_relationship_thumbnails($title, $post, $field, $the_post){
    if( in_array(‘featured_image’, $field[‘result_elements’]) ) {
    if( $post->post_type == ‘attachment’ ) {
    Use:
    function acf_relationship_thumbnails($title, $post, $field, $post_id){
    if( in_array(‘featured_image’, $field[‘elements’]) ) {

    Reply

Leave a Reply