scribu / wp-posts-to-posts

Efficient many-to-many connections between posts, pages, custom post types, users.
http://wordpress.org/plugins/posts-to-posts/
975 stars 261 forks source link

P2P don't change main querie with pre_get_posts action hook #539

Open mfrerebeau opened 7 years ago

mfrerebeau commented 7 years ago

I want to change home main querie to have only post that is connected to a specific custom post.

The result is that query vars doesn't change anything...

The connexion :

  p2p_register_connection_type( array(
      'name' => 'magazine_post',
      'from' => 'magazine',
      'to' => 'post',
      'cardinality' => 'one-to-any', 
      'admin_box' => array(
        'show' => 'any',
        'context' => 'advanced' 
      ),
    ));

pre_get_posts action :

function my_alter_query($query){
  if( $query->is_main_query() ){
    if( !is_admin() ) {
      // Recherche la dernière revue saisie dans la base et l'enregistre en variable globale
      global $current_magazine;
      $current_magazine = get_posts( array (
        'post_type' => 'magazine',
        'posts_per_page' => 1,
      ));
      if( !empty( $current_magazine ) ) 
        $current_magazine = $current_magazine[0]; // Récupère le seul élément de la liste
      else
        $current_magazine = null;
      if( is_home() ) {
        $query->set( 'connected_type', 'magazine_post' );
        $query->set( 'connected_from', $current_magazine );
        $query->set( 'nopaging', true );
      }
    }
  }
}
add_action('pre_get_posts','my_alter_query');

However, if I make a custom query as follow, it runs :

      $my_query = new WP_Query( array(
        'connected_type' => 'magazine_post',
        'connected_from' => $current_magazine,
        'nopaging' => true,
      ) );
      print_r( $my_query->get_posts() );

So when we make a custom WP_Query object it's ok. But when we change main query P2P don't run. Do you know Why ? I've don't see other issue about that problem...

ArnaudBan commented 3 years ago

I found the answer here : https://github.com/scribu/wp-posts-to-posts/issues/309#issuecomment-18811331