0
votes

I have a custom post type of products, and each product belongs to a product category. I am trying to query the products to get all products sorted alphabetically by their product category i.e.

First:
Product: Lion
Category: Animals

Last:
Product: Snowmobile
Category: Winter

I am using a custom field for the product category, but my query doesn't sort them alphabetically - but instead by which date they are published. The product_cat_meta field is a regular text field set up in custom fields. Query is here:

function get_products()
{


  $args = array(
    'post_type' => 'products',
    'post_status' => 'publish',
    'meta_key' => 'product_cat_meta',
    'orderby' => 'meta_value',
    'order' => 'ASC',
    'posts_per_page' => -1
  );

  $products = new WP_Query($args);    
  if ($products->have_posts()) {
    $index = 0;
    while ($products->have_posts()) {
      $products->the_post();

      $prod_meta = get_field('product_cat_meta');
      echo $prod_meta;

      );
      $index++;
    } // end while
  } // end if
}

The result of this query just returns the prod category in the way they are set up in wordpress – the latest posts first, but not sorted alphabetically

1
Have you tried using Category Parameters? - aagjalpankaj
The product category is its own post type, so I don't have any category parameters available for the products unfortunately. Instead it is two custom fields where one links to the category page, and the other is just plain text of the category. - user2868900
Are you sure that you are using right meta_key ? Because your query is correct. - shazyriver

1 Answers

0
votes

You can try to put the code in functions.php file.

The code, which can be dropped into your current theme’s functions.php if you like:

function get_products()
{
  $args = array(
    'post_type' => 'products',
    'post_status' => 'publish',
    'meta_key' => 'product_cat_meta',
    'orderby' => 'title',
    'order' => 'ASC',
    'posts_per_page' => -1
  );

  $products = new WP_Query($args);    
  if ($products->have_posts()) {
    $index = 0;
    while ($products->have_posts()) {
      $products->the_post();

      $prod_meta = get_field('product_cat_meta');
      echo $prod_meta;

      );
      $index++;
    } // end while
  } // end if
}

Get More details, follow the link: https://codex.wordpress.org/Alphabetizing_Posts