scribu / wp-posts-to-posts

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

pre_get_posts in admin #559

Open benjaminniess opened 6 years ago

benjaminniess commented 6 years ago

Hello,

First of all thank you @scribu for your plugin. I've been using it for years now and it's still very useful.

I'm running into a little problem trying to limit admin posts list with p2p arguments.

Basically, I'm using the pre_get_posts hook in admin, I'm on the main query and I try to add some P2P query args like so:

$query->set( 'connected_type', 'my_connected_type');
$query->set('connected_items', $my_connected_items);

Unfortunately, it has no effect on the posts list even if I see my params in the global $wp_query variable.

If in this same pre_get_posts hook I initiate a second WP_Query with the same P2P params, I do receive the posts I want and I can use them with:

$query->set('post__in', $my_posts);

But it means that I need to run 2 queries. Is it something you've already experimented and do you have a chance to have a look at it?

Thanks again. Ben

mfrerebeau commented 6 years ago

Hi, I have the same problem. Do you have found a solution ?

mfrerebeau commented 6 years ago

Ok : I found 2 solutions Source : https://github.com/scribu/wp-posts-to-posts/issues/483#issuecomment-136774748

With pre_get_post hook you can add the command : P2P_Query_Post::parse_query( $query );

You can use instead of pre_get_post the parse_query hook : then P2P can run.

ipetak commented 4 years ago

If anyone still has problems with this the above solution is correct but when in admin you don't need to call the static method again, simply hook your function on "parse_query" with priority less than 20 since on 20 P2P parses query by default.

If you're getting WordPress database error Operand should contain 1 column(s) error it means your arguments are being hooked into the distributed connections query as well and you simply need to check for specific post type before setting the query args.

function my_custom_args( $query ) {
  if ( your post type === $query->get( 'post_type' ) ) {
      $query->set( 'connected_type', your connection type );
      $query->set( 'connected_items', your connected items );
      $query->set( 'nopaging', true );
  }
} 
add_action( 'parse_query', 'my_custom_args' );