I am trying to set ‘meta_query’ programaticaly for a filter which is supposed to filter a custom post type depending on the existence of a metakey. I have tried several ways, which I have left in the below code, commented out. None of the solutions change the actual $query ‘meta_query’ property, which stubbornly remains set to ‘false’.
I have a feeling that i’m missing something basic. Please assist. Thank you.
add_filter( 'parse_query', 'filter_posts_by_no_associated_contact' );
function filter_posts_by_no_associated_contact( $query ) {
global $pagenow;
$qv = &$query->query_vars;
if( $pagenow == 'edit.php' &&
isset($qv['post_type']) && $qv['post_type'] == 'act'
&& isset($_GET['contact_status']) && $_GET['contact_status'] != '' ){
$compare = ( $_GET['contact_status'] == 'with_contact' ) ? 'EXISTS' : 'NOT EXISTS';
// $query->meta_query[] = array(
$metaquery = array(
'key' => 'contact_associated',
'value' => 'justAstring',
'compare' => $compare,
'type' => 'CHAR'
);
$query->set( 'meta_query', $metaquery );
}
}
i have seen this done elsewhere:
$qv = &$query->query_vars;
$qv['meta_query'] = array();
$qv['meta_query'][] = array(
'field' => 'meta-key',
'value' => $whatever,
'compare' => '',
'type' => ''
);
But this solution results in a php “Warning: Attempt to modify property of non-object”.
meta_query
has to be an array of arrays. You only have an array.return
information. Yours doesn’t.parse_query
is an action not a filter, despite your use ofadd_filter
. Useadd_action
instead.pre_get_posts
instead ofparse_query
. It is the nexthook that fires after
parse_query
(check the source) and your code works more or less as expected if you use that hook, assuming the change mentioned in item #1.