Programmatically set ‘meta_query’ for filter

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.

Read More
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”.

Related posts

1 comment

    1. A meta_query has to be an array of arrays. You only have an array.
    2. A filter needs to return information. Yours doesn’t.
    3. Of course, parse_query is an action not a filter, despite your use of add_filter. Use add_action instead.
    4. I would use pre_get_posts instead of parse_query. It is the next
      hook 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.

Comments are closed.