I am trying to create custom filters for my users. Here is what i am trying to do which doesn't work:
$args = array(
'post_type' => 'books',
'meta_key' => 'product_title',
'orderby' => 'meta_value_num',
'order' => 'ASC',
'posts_per_page' => -1,
'relation' => 'OR',
'options' => array()
);
foreach ($myurlfilter as $multifilter) {
$args['options'][] = array (
'key' => 'product_title',
'value' => "$multifilter",
'compare' => 'LIKE',
);
}
I don't get any php error and i don't know what i am doing wrong. I did made my code according to this answer: Foreach loop inside array and if you check the last comment of the author at below answer it say "code does not work".
From the output i see, i believe the options from foreach code are not "connecting" properly with code above it.
If that helps what i am trying to achieve with foreach is something like this, which works perfect:
$args = array(
'post_type' => 'books',
'meta_key' => 'product_title',
'orderby' => 'meta_value_num',
'order' => 'ASC',
'posts_per_page' => -1,
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'product_title',
'value' => 'Leonardo',
'compare' => 'LIKE',
),
array(
'key' => 'product_title',
'value' => 'Einstein',
'compare' => 'LIKE',
)
)
);
CodePudding user response:
Try building your meta query with the starting "or"
$myMeta = array( 'relation' => 'OR' );
foreach ($myurlfilter as $multifilter) {
$myMeta[] = array (
'key' => 'product_title',
'value' => $multifilter,
'compare' => 'LIKE',
);
}
$args['meta_query'][] = $myMeta;
I also belive you need to ditch "options" and add to "meta_query"
$args = array(
'post_type' => 'books',
'meta_key' => 'product_title',
'orderby' => 'meta_value_num',
'order' => 'ASC',
'posts_per_page' => -1,
'meta_query' => array() // change this, remove the relation
);