Order by Custom Field date not recognized

I can’t get a meta_key parameter to pass through a GET string at all. Many other parameters that I tested do pass through, though I did not do an exhaustive test, but meta_key does not.

If you want to verify that just add the following to the top of your header.php and inspect the query.

echo '<pre>'; 
var_dump($wp_query); die;
echo '</pre>';

I have never tried to pass that parameter before now but checking the Codex (thanks @birgire), I see that meta_key is listed as a “Private” variable. You cannot pass private variables through an URL, even if the parameters are valid if passed directly to WP_Query via hard-coded PHP.

What you are attempting, seems to be intentionally not allowed. You can only modify the query via an URL using the parameters listed as “Public”. Other parameters are ignored, as you can see by inspecting the query as above.

That aside, when I see “ordering” problems like that the first thing I suspect are sticky posts. If you were using WP_Query directly I’d suggest that you add &ignore_sticky_posts=true but I can’t get that to pass through GET either.

However, if you really must, you should be able to force this through with a filter on pre_get_posts.

function order_by_meta($qry) {
  if (isset($_GET['meta_key']) && $_GET['meta_key'] == 'wpcf-evento-data-inicio1') {
    $qry->set('meta_key','wpcf-evento-data-inicio1');
  }
}
add_action('pre_get_posts','order_by_meta');

Leave a Comment