Hi,
Does anyone have any code for a function or shortcode which does this:
1. Get the value of ACF field (let’s say ‘location’) for the current custom post type that the shortcode is displayed in.
2. Show x related posts from the same custom post type and the same value for ACF field ‘location’.
many thanks
Hi @neodjandre
Do you mean you want to get the custom field value from inside a custom shortcode? I believe you can do that by passing the current post ID to the get_field()
function like this:
// Get the current post object first
global $post;
$location = get_field('location', $post->ID);
To get the related posts, you can always query them based on custom field value like this:
// get the value without the formatting so we can search it in the database
$location = get_field('location', $post->ID, false);
$posts = get_posts(array(
'numberposts' => 5,
'post_type' => 'custom-post',
'meta_key' => 'location',
'meta_value' => $location
));
This page should give you more idea about it: https://www.advancedcustomfields.com/resources/query-posts-custom-fields/.
I hope this helps 🙂