Home > front end >  Display acf taxonomy attachment the_content
Display acf taxonomy attachment the_content

Time:01-03

On wordpress, using ACF I've added a taxonomy field to the attachment to all images. I now want to display the taxonomy field in the html 'id="the-taxonomy">'. My main goal is using it as an anchor. So you'd go to my website - Fakewebsite.com/work/toast#the-taxonomy.

I cannot seem to display the taxonomy tag in the html. At the moment it is just displaying the first random tag. (apples)

The html looks like this - https://paste.pics/98d4ab6b52b0951c31df62b54534b1b7 and the attachment looks like this: https://paste.pics/06d35483028b09520dc3d822d10d06e5 At the moment it says id="Apples" I want it to say "business card"

Id appreciate any help. Thank you.

<?php
add_filter('the_content','new_content');
function new_content($content) {

    $term = get_queried_object();
    $test = get_field('tag_cat_acf', get_post_thumbnail_id());

    {

        $content = str_replace('<img ', '<img data-attr="'.  $test->name .'" ', $content);
        return $content;
    }
}
?>

CodePudding user response:

I think I understand what you're looking for, and I think your approach isn't quite the way I would go.

I used this filter wp_get_attachment_image_attributes. Which allows you to add attributes to media items. Then you can use this filter to get the media item id, and retrieve the ACF field.

add_filter( 'wp_get_attachment_image_attributes', 'dd_custom_attribute_acf', 10, 2 );
/**
 * Filter the media item to add an ACF data-attribute to an image.
 *
 * @param array  $attr - The media item attributes.
 * @param object $attachment - The media item post object.
 * @return array
 */
function dd_custom_attribute_acf( $attr, $attachment ) {
    // get_field of whatever your field name is here.  
    $attr['data-attr'] = get_field( 'tag_cat_acf', $attachment->ID );
    return $attr;
}

I added this to my functions.php and it did add the contents of my custom field to the image html.

  • Related