1

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".

1 Answer 1

5
  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.
1
  • Many thanks, it indeed needed to be in another array. btw. why do you suggest pre_get_posts instead of parse_query? Mar 11, 2014 at 11:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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