Advertisement
SergeyBiryukov

Filter by custom fields

Apr 19th, 2016
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.50 KB | None | 0 0
  1. function filter_by_custom_fields( $query ) {
  2.     $custom_fields = array(
  3.         'frame_height',
  4.         // ...
  5.     );
  6.  
  7.     $meta_query = array();
  8.  
  9.     foreach ( $custom_fields as $field ) {
  10.         if ( ! isset( $_GET[ $field ] ) ) {
  11.             continue;
  12.         }
  13.  
  14.         $meta_query[] = array(
  15.             'key'     => $field,
  16.             'value'   => sanitize_text_field( $_GET[ $field ] ),
  17.             'compare' => 'LIKE',
  18.         );
  19.     }
  20.  
  21.     if ( $meta_query ) {
  22.         $query->set( 'meta_query', $meta_query );
  23.     }
  24. }
  25. add_action( 'pre_get_posts', 'filter_by_custom_fields' );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement