0

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.

2 Answers 2

1

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;
}
1
  • Thanks! That must be the best method :) I get no more Undefined index while the code is shorter.
    – wpStudent
    Commented Dec 3, 2010 at 0:38
2

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;
0

Your Answer

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

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