• I’m building a simple “Links gallery” using ACF. The obvious approach is to add 2 ACF fields: ACF Image and ACF URL. But how do I turn them into one ACF Block for the image with a custom link? Do I really need to register a new rest field (as described in your stickied post)? In any case I cannot get it to work. :/

    Maybe you have time to provide a code snippet for this user case?

    • This topic was modified 1 year, 11 months ago by jonohlsson.
Viewing 4 replies - 1 through 4 (of 4 total)
  • Plugin Author Phi Phan

    (@mr2p)

    Hi @jonohlsson, You may don’t need to register a custom rest field if you don’t like it. Could you give me the names of your two fields? I will give you the working code for your use case.

    Thanks, Phi.

    Plugin Author Phi Phan

    (@mr2p)

    Hi @jonohlsson,

    Here is the snippet code for your use case:

    add_filter(
      'meta_field_block_get_block_content', function ( $content, $attributes, $block, $post_id ) {
        $field_name = $attributes['fieldName'] ?? '';
        if ('your_image_field' === $field_name) {
          $url = get_field( 'your_url_field', $post_id );
          if ( esc_url($url) ) {
            $content = sprintf( '<a href="%1$s">%2$s</a>', esc_url( $url ), $content );
          }
        }
        return $content;
      }, 10, 4
    );

    You should change your_image_field, your_url_field to your real field names.

    Thanks, Phi.

    Thread Starter jonohlsson

    (@jonohlsson)

    Fantastic. Thanks!

    But for some reason the $content array only held an integer, not the image object. So I had to do an ugly workaround:

    add_filter( 'meta_field_block_get_block_content', function ( $content,$attributes, $block, $post_id ) { 
      $field_name = $attributes['fieldName'] ?? ''; 
       if ('your_image_field' === $field_name) { 
        $url = get_field( 'your_url_field', $post_id ); 
        $image = get_field( 'your_image_field', $post_id );
        if ( esc_url($url) ) {
        $content = sprintf( '<a href="%1$s"><img src="%2$s"></a>', esc_url( $url ), $image ); 
        } 
       } 
    return $content; }, 10, 4 );

    When I added a standard Meta field block for only the image it was rendered correctly.

    Plugin Author Phi Phan

    (@mr2p)

    @jonohlsson I’m glad it works now. I forgot to mention that you should set the field name as the image field, the URL field will be gotten in the code.

    Thanks, Phi.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘ACF Image with custom link’ is closed to new replies.