WordPress: Get posts from two custom fields in meta query

464 Views Asked by At

I'm using a Custom Post Type to store recipes. Every recipe is related to certain products and categories.

In a product I want to display recipes related to it. So first I want to show recipes which have the product ID in the custom field recipe_related_products and after that I want to show recipes which have the current product category in the custom field recipe_related_product_cats.

I'm using the ACF relationship field for that.

Here's my code:

$recipes = get_posts(array(
    'post_type' => 'recipes',
    'meta_query' => array(
        'relation' => 'OR',
        array(
            'key'     => 'recipe_related_products',
            'value'   => '"' . get_the_ID() . '"',
            'compare' => 'LIKE',
        ),
        array(
            'key'     => 'recipe_related_product_cats',
            'value'   => '"' . $cat_id . '"',
            'compare' => 'LIKE',
        ),
    ),
));

The code shows only recipes from the field recipe_related_products. It seems that 'relation' => 'OR' has no effect.

If I remove the first array from the meta_query I get the recipes which are in the recipe_related_product_cats.

Is the 'relation' => 'OR' the problem? It seems that booth meta queries are correct but they don't work together?!

To get the current ID from the product I'm using this code:

$cat_list = wp_get_post_terms($product->get_id(),'product_cat',array('fields'=>'ids'));
$cat_id = (int)$cat_list[0];
0

There are 0 best solutions below