Support

Account

Home Forums General Issues How to show related posts based on custom fields?

Helping

How to show related posts based on custom fields?

  • I am trying to create a ‘Posts you may like’ sidebar that features thumbnails/titles of 3 related posts, based on values from ACF inputs.

    In particular, I would like to show posts that have the same value for a field called ‘district’ AND that have a value +/- 50 of a field called ‘price’. I have been looking around the support threads for a similar question and couldn’t find one, can any give me a code snippet or point me to a thread that may help? Thanks!

  • To do this you’re going to have to do a new WP_Query on these meta values. Something like this.

    
    $district = get_field('district');
    $price = get_field('price');
    $low = $price-50;
    $high = $price+50
    $args = array(
      'post_type' => 'your-post-type',
      'post_per_page' => 3,
      'meta_query' => array(
        array(
          'key' => 'district',
          'value' => $district
        ),
        array(
          'key' => 'price',
          'value' => $low,
          'compare' => '>='
          'type' => 'NUMERIC'
        ),
        array(
          'key' => 'price',
          'value' => $high,
          'compare' => '<='
          'type' => 'NUMERIC'
        )
      )
    );
    $query = new WP_Query($args);
    

    see https://codex.wordpress.org/Class_Reference/WP_Query

    also https://www.advancedcustomfields.com/resources/query-posts-custom-fields/

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

The topic ‘How to show related posts based on custom fields?’ is closed to new replies.