Question

Thanks to your suggestions, I enabled wp_debug and discovered flaws with my plugin. I have a filter for sorting posts by votes. I use it when the sort URL parameter is on.

add_filter( 'posts_where', 'votes', 10, 2 );

I used to get Undefined index: sort so I modified my function to first check if the variable is set.

function votes( $where, $query )
{
  $sort = array_key_exists('sort', $query->query_vars) ? $_GET['sort'] : null;
  if ( isset($sort) ) {         
       $where .= " AND $sort >= votes";               
  }
  return $where;
}

This works fine but I'm not confident if it's correct. I'm wondering if there's a better method to do this.

Was it helpful?

Solution

The variable you have named $query is actually the WP_Query instance having filters applied to it.

You can simply call its function get to retrieve query vars.

For example:

function votes( $where, $query )
{
    $sort = $query->get('sort');
    if (!empty($sort)
        $where .= " AND $sort >= votes";
    return $where;
}

OTHER TIPS

If you check for $query->query_vars first but then use $_GET['sort'] later on, you have just checked or used the wrong variable. I think this just happened when you edited the script.

you probably wanted to write this:

 $sort = array_key_exists('sort', $query->query_vars) ? $query->query_vars['sort'] : null;
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top