0

I want to add a complex filtering when getting my products.

  • I have products where some of them are linked to a custom post type.
  • This custom post type has a repeater field.
  • Depending on a cookie, I should only get products that have that value in this repeater field

I know I can use:

add_filter( 'pre_get_posts', 'fwp_archive_per_page' );

I know i can set extra meta query like this:

$query->set( 'meta_query', array(
    'relation'    => 'AND',
        array(
            'key'   => 'xxx',
            'value'     => 'xxx'
        )
));

But this is more complex as I should do a query on every product ID to check if the value exists in the repeater field from the related custom post type.

Anyone has a clue how to do this?
Or is there another way around to handle this?

2

When I have complex querie to do, I often use a prequery to get the good post_ids. Then I pass this list of post_ids to my main query via the post__in parameter of WP_Query.

$meta_key = 'RepeaterName_%_FieldName';
$meta_value = 'MyCustomValue';

global $wpdb;
$post_ids = $wpdb->get_col( $wpdb->prepare( 
    "
        SELECT      pm.post_id
        FROM        $wpdb->postmeta pm
        WHERE       pm.meta_key LIKE %s 
        AND         pm.meta_value = %s
    ",
    $meta_key, 
    $meta_value, 
) ); 
// Or with another custom $wpdb request 
// https://developer.wordpress.org/reference/classes/wpdb/

Then we add $post_ids to main query

if ( !empty( $post_ids ) ) {
    $post__in = $query->get('post__in');
    if ( empty( $post_in ) ) {
        $query->set( 'post__in', $post_ids );
    } else {
        $query->set( 'post__in', array_intersect( $post_ids, $post__in ) )
    }
}

All this code must be placed in the pre_get_posts filter. I hope that the response is up to your expectations.

Not the answer you're looking for? Browse other questions tagged or ask your own question.