How to add another parameters to WP_Query?

I need to do something like that:

        $postsOrder = get_sub_field('posts-ordering');

        if ($postsOrder="post_views_count") {
            $queryPopular = array (
                'meta_key' => 'post_views_count',
                'orderby' => 'meta_value_num',
            );
        }

        $query = new WP_Query(
            array(
            'posts_per_page' => $postsCount,
            'post_type' => $postsType->name,
            'order' => 'DESC',
            'orderby' => $postsOrder,
            'taxonomy' => $postsTaxonomy,
            $queryPopular
            ),
        );

The point is that if $postsOrder is equal ‘post_views_count’, then in $query should be added two another parameters. How to do it right?

1 Answer
1

You can use below code to add other two parameter as condition.

  $args = array(
      'posts_per_page' => $postsCount,
      'post_type' => $postsType->name,
      'order' => 'DESC',
      'orderby' => $postsOrder,
      'taxonomy' => $postsTaxonomy,
  );

  $postsOrder = get_sub_field('posts-ordering');

  if ($postsOrder == 'post_views_count') {
      $args['meta_key'] = 'post_views_count';
      $args['orderby'] = 'meta_value_num';
  }
  $query = new WP_Query($args);

Leave a Comment