php - Wordpress: Filter Posts Custom Field Value Based on URL Parameter -


i added custom 'checkbox' field each of post of plugin called advanced custom field. field name 'country' , according plugin author,

enter each choice on new line.for more control, may specify both value , label this: red : red blue : blue

my own value , label go this:

us: usa

fr: france

now, want filter posts based on 'country' field value. when url example.com?country=us, should display posts related usa.

i added below code functions.php it's not working.

function my_pre_get_posts( $query ) {  // not modify queries in admin if( is_admin() ) {      return $query;  }  if( isset($query->query_vars['post_type'] && $query->query_vars['post_type'] == 'post')) {      // allow url alter query     if( isset($_get['country']) ) {          $query->set('meta_key', 'country');         $query->set('meta_value', $_get['country']);      }   }   // return return $query;  } 

i'm noob when comes php. doing wrong?

updated:

when first tried it, didn't work @ all. when tried login admin page. got error:

xdebug: fatal error: cannot use isset() on result of expression (you can use "null !== expression" instead) in \wp-content\themes\functions.php on line 14

the code on line 14

if( isset($query->query_vars['post_type'] && $query->query_vars['post_type'] == 'post')) 

the error message telling , issue is... cannot use isset() on result of expression in line if( isset($query->query_vars['post_type'] && $query->query_vars['post_type'] == 'post'))

the code isn't working because if statement in line 14 cannot evaluate correctly.

isset takes variable (or number of variables) parameter - passing in entire expression if statement, not allowed. use isset check if variable set , isn't null before check ref: http://php.net/manual/en/function.isset.php.

you need change line 14 of code following:

if(      isset($query->query_vars['post_type']) // check if post_type query var has value     &&                                     // , if does...     $query->query_vars['post_type'] == 'post'  // ... check if == "post" )  

it can on same line in example (as long remove comments)... i've split out highlight different parts of expression evaluating.


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -