Leave a Reply

2 comments

  1. That’s because ‘meta_key’ and ‘meta_value’ are not public query vars. In other words, you can’t use them in URLs directly, nor should you.

    Instead, register a specific query var, like so:

    function register_my_qv() {
      global $wp;
      $wp->add_query_var( 'my_qv' );
    }
    add_action( 'init', 'register_my_qv' );
    

    Then, you can go to a URL like this: ?my_qv=foobar

    All you need to do now is map your query var to the actual query you want to do:

    function map_my_qv( $wp_query ) {
      if ( $meta_value = $wp_query->get( 'my_qv' ) ) {
        $wp_query->set( 'meta_key', 'some_meta_key' );
        $wp_query->set( 'meta_value', $meta_value );
      }
    }
    add_action( 'parse_query', 'map_my_qv' );
    
  2. I can’t add a comment to the scribu’s excellent answer due to low reputation, but still the second part of the code (map_my_qv function) while working on WP 4.2 was giving me 404s, missing posts in admin and PHP notices about $meta_value variable not set. Therefore, here’s the edited code:

    function map_my_qv( $wp_query ) {
        if ( is_admin() || ! $wp_query->is_main_query() ) 
            return; 
    
        if ( $wp_query->get( 'my_qv1' ) ) {
            $wp_query->set( 'meta_key', 'my_meta_key1' );
            $wp_query->set( 'meta_value', $wp_query->get( 'my_qv1' ) );
        }
        if ( $wp_query->get( 'my_qv2' ) ) {
            $wp_query->set( 'meta_key', 'my_meta_key2' );
            $wp_query->set( 'meta_value', $wp_query->get( 'my_qv2' ) );
        }
    }
    add_action( 'parse_query', 'map_my_qv' );