Support

Account

Home Forums General Issues Related Posts based on ACF Fields

Helping

Related Posts based on ACF Fields

  • 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 🙂

Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘Related Posts based on ACF Fields’ is closed to new replies.