Skip to content

Instantly share code, notes, and snippets.

@git-bhanu
Last active November 7, 2020 10:58
Show Gist options
  • Save git-bhanu/2ffa7e6e851f877b5b807567e9bd23f4 to your computer and use it in GitHub Desktop.
Save git-bhanu/2ffa7e6e851f877b5b807567e9bd23f4 to your computer and use it in GitHub Desktop.

Get all the possible materials for a particular type of product which have $maincatergory (say Mens | product_cat) marked in them.

    public static function getMaterials($search_term, $maincategory) {

      $return_arr = a(array());

      $terms = a(array());

      $args  = array(
        's' => $search_term,
        'post_type' => 'product',
        'posts_per_page' => -1,
        'post_status' => 'publish',
        'tax_query'     => array(
            array(
                'taxonomy'  => 'product_cat',
                'field'     => 'id',
                'terms'     => $maincategory,
            )
          )
        );

    $query = new \WP_Query($args);
    $query->parse_query($args);

    relevanssi_do_query( $query );

    foreach ( $query->posts as $post ) {
      $term_obj_list = get_the_terms( $post->ID, 'material' );
      if($term_obj_list == null) {
        continue;
      }
      foreach($term_obj_list as $term) {
        $terms->appendArrayValues([$term], $term->term_id);
      }
    }

    $taxonomy = 'material';

      foreach ($terms as $term) {

          $buffer = a(array());
          $id = $term->term_id;
          $name = $term->name;

          $buffer->appendArrayValues([$id], 'id')
                 ->appendArrayValues([$name], 'name')
                 ->appendArrayValues([false], 'value');

          $return_arr->appendArrayValues([$buffer->toArray()], $id);
      }
      return $return_arr->toArray();
  }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment