building filtering system

Question

I’ve currently built a simple filtering system, and I am pretty new to wordpress and want to know why this method works fine in index.php:

$GLOBALS['my_query_filters'] = array(
'field_1' => 'type',
'field_2' => 'color',
'field_3' => 'size',
);

 foreach ($GLOBALS['my_query_filters'] as $key => $name) {
  if (empty($_GET[$name])) {
      continue;
  }
  $value = explode(',', $_GET[$name]);
  $args = array(
      'post_type' => 'project',
      'post_status' => 'public',
      'meta_key' => $name,
      'meta_value' => $value,
      'compare' => 'IN',
  );
 }
  $backup = array(
     'post_type' => 'project',
     'post_status' => 'public',
 );

 $loop = new WP_Query(($args ?? $backup));

 while ( $loop->have_posts() ) : $loop->the_post();
// RENDERING OUT THE CONTENT HERE:
 ?>

but this solution in functions.php, seems to break the way my content renders out on the page (especially talking about date format, being 20200815 like this instead of: 2020.08.15 for example:

  $GLOBALS['my_query_filters'] = array(
     'field_1' => 'type',
     'field_2' => 'color',
     'field_3' => 'size',
 );

  function my_pre_get_posts($query)
  {
   if (is_admin()) {

       return $query;

   }
   foreach ($GLOBALS['my_query_filters'] as $key => $name) {
      if (empty($_GET[$name])) {
          continue;
      }
      $value = explode(',', $_GET[$name]);
      $meta_query[] = array(
        'post_type' => 'project',
        'post_status' => 'public',
        'key' => $name,
        'value' => $value,
        'compare' => 'IN',
      );
  }

  if (!empty($meta_query)) {
    $query->set('meta_query', $meta_query);
   }

   return $query;
  }
   add_action('pre_get_posts', 'my_pre_get_posts');

Some background info: this is a system that filters out custom fields that are added to list of project posts

0
suiteguy 8 months 2020-12-05T11:10:23-05:00 0 Answers 6 views 0

Leave an answer

Browse
Browse