I'm using ACF (Advance Custom Fields) for Media Uploads to store location information about photos. When I set a post Featured Image to a photo that has this extra field, I'd like to output the location information from this Custom Field.
Basically, I need a shortcode that will output an ACF Custom Field of the Current Post's Featured Image.
I'm using ACF (Advance Custom Fields) for Media Uploads to store location information about photos. When I set a post Featured Image to a photo that has this extra field, I'd like to output the location information from this Custom Field.
Basically, I need a shortcode that will output an ACF Custom Field of the Current Post's Featured Image.
Share Improve this question asked Feb 17, 2021 at 14:22 Rob JacksonRob Jackson 1 2- Your best bet is to ask the ACF developers how to go about doing this; ACF works different than standard WP and WPSE is intended for development/programming questions that are directly within WordPress and not third party methods. – Tony Djukic Commented Feb 17, 2021 at 18:45
- I contacted the ACF developers who said to hire a freelancer – Rob Jackson Commented Feb 18, 2021 at 0:17
1 Answer
Reset to default 0The most basic option I can think of is this
add_shortcode('bt_featured_image_acf_location', 'bt_featured_image_acf_location');
function bt_featured_image_acf_location ($atts) {
return get_field('location', get_post_thumbnail_id());
}
Change 'location' to your acf field name and thats it.
get_post_thumbnail_id()
will get the current post featured image id.
Once you have the ID of the post (images are posts, they are of the post type, attachment) that you want to get the ACF fields from you can pass it to get_field()
in the second argument and you're done.
Change it how ever you want and add as much logic as you need, this is the best I can do with the information you provided
EDIT
If you use this shortcode inside a post template single.php
, this shortcode works fine.
If you would like to display it anywhere else you will need to pass the post id manually.
Below the edited shortcode that can accept post id
add_shortcode('bt_featured_image_acf_location', 'bt_featured_image_acf_location');
function bt_featured_image_acf_location ($atts) {
$atts = shortcode_atts([
'post_id' => get_the_ID()
], $atts);
return get_field('location', get_post_thumbnail_id($atts['post_id']));
}
Now this shortcode will still work the same way, but now you can pass it the post id
regular way to call it
echo do_shortcode('[bt_featured_image_acf_location]')
call the shortcode with post id
echo do_shortcode('[bt_featured_image_acf_location post_id="5526"]')