Support

Account

Home Forums General Issues How to exclude posts from loop that are in a relationship

Solving

How to exclude posts from loop that are in a relationship

  • Hey!
    I need to exclude posts from a loop that are in a relationship (in a group of posts). How is this possible?

    At the moment i am using something like this:

     function ingruppe($id)	{
     	$gruppe="";
     	$check_in_gruppe = get_posts(array(
     		'post_type' => array ('veranstaltungsgruppe'),
     		'meta_query' => array(
     			array(
     				'key' => 'veranstaltungen', 
     				'value' => '"' . $id . '"', 
     				'compare' => 'LIKE'
     				)
     			)
     		));
     	if ( ! empty( $check_in_gruppe ) ) {
     		return true;
    }
    }

    and in the loop

    
    if (!ingruppe(get_the_ID()))
    	    			{ … }
    

    but how is this possible to work with pre_get_posts or similiar to exclude the posts from the loop?

    thank you!

  • Hi @buckdanny

    Hmm… Try this, in pre_get_posts grab the value of the relationship field using get_field(...). get_field(...) will return an array of the selected posts. Loop through this array and create your meta_query $args dynamically. Then in your meta_query, use the “NOT LIKE” compare instead of the “LIKE” compare so that the query can exclude the selected posts.

    I’ve never tried this but I think it should work. Give it a try and let me know how it goes 🙂

    You can read more on meta_query here: https://codex.wordpress.org/Class_Reference/WP_Meta_Query

  • Hey! thank you very much, this sounds good!
    I tried it like this, at the moment the query does not run but I have an array with all ids of posts in relationship. What do you think, will this work solid?
    Why the query is not updating?

    the code is just a sketch at the moment:

    
    function ingruppe_pre_get_post( 	$the_query ) {
    
    	 wp_reset_postdata();
    
    	
    	$alle_posts_in_gruppen = array();
    
    if( ! is_admin() &&	$the_query->is_main_query() ) {
    	
    	$check_in_gruppe = get_posts(array(
     		'posts_per_page' => '-1',
     		'post_type' => array ('veranstaltungsgruppe'),
     		'meta_key' => 'veranstaltungen',
     
    
     				
     		));
    
    	foreach ($check_in_gruppe as $check_in_gruppe_i){
    		
    			$beziehung = get_field('veranstaltungen', $check_in_gruppe_i->ID);
    			
    			foreach	($beziehung as $beziehung_i) {
    				
    				$alle_beziehungen [] = $beziehung_i->ID;
    				
    			}	
    	}
    	
    	echo "<br>exclude this posts because they are in relationship: <br>";
    					print_r($alle_beziehungen);
    
     			$the_query->set('post__not_in', $alle_beziehungen);
     			
     			
     			///test Query dont update…:
    			$the_query->set('posts_per_page', 1);
    
    

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

The topic ‘How to exclude posts from loop that are in a relationship’ is closed to new replies.