Support

Account

Home Forums General Issues How to exclude current page from acf relationship query

Solved

How to exclude current page from acf relationship query

  • Hello. I have acf option page with the field Relationship. I display this block on many pages of the site. How can I exclude the current page from the list of displayed pages?

    My code for Relationship:

    <?PHP $coin_pages = get_field('sb_sector_pages_pages', 'option');
                if( $coin_pages ): 
                foreach( $coin_pages as $post ) : 
                    $permalink = get_permalink( $post->ID );
                    $thumbnail = get_the_post_thumbnail( $post->ID, 'full');
                    $title = get_the_title( $post->ID );
                    setup_postdata($post); ?>
                        <li class="coin-article__sidebar-list-item">
                            <a href="<?php echo esc_html( $permalink ); ?>" class="coin-article__sidebar-list-link">
                                <div class="coin-article__sidebar-coin-ico">
                                    <?php echo $thumbnail; ?>
                                </div>
                                <span class="coin-article__sidebar-coin-title"><?php echo esc_html( $title ); ?></span>
                            </a>
                        </li>
                <?php endforeach; ?>

    I tried to add this to my functions.php but it doesn’t work for me:

    add_filter('acf/fields/relationship/query/name=sb_sector_pages_pages', 'exclude_id', 10, 3);
    function exclude_id ( $args, $field, $post ) {
    		$args['post__not_in'] = array( $post );
    		return $args;
    }
  • The acf/fields/relationship/query/ only works in the admin when editing fields.

    If you want to do this on the front end there are couple of choices.

    The first it to compare the current post ID with the value in the loop and is probably the simplest and how I would go.

    
    // before the loop
    $current_post_id = $post->ID;
    
    // inside your loop before showing anything about the post
    if ($post->ID == $current_post_id) {
      // skip this post
      continue;
    }
    

    The other method would be to use your function as a pre_get_posts filter that is added before you get the value of the ACF field and removed after you get the value.

    
    // change to your function
    function exclude_id ($query) {
      $query->set('post__not_in', array(get_queried_object_id()));
    }
    
    
    //change to your template code
    add_action('pre_get_posts', 'exclude_id');
    $coin_pages = get_field('sb_sector_pages_pages', 'option');
    remove_filter('pre_get_posts', 'exclude_id');
    
Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.