Meta_query in WooCommerce

I’m trying to use the meta_query in WooCommerce product page.

This is the code I’m using:

Read More
  <?php
  $args = array(
      'post_type' => 'product',
      'posts_per_page' =>8,
      'meta_query' => array(
            array(
                'key' => 'autor',
                'value' => '"'.get_the_ID().'"',
                'compare' => 'LIKE',
            )
      ),
  );
  $products = new WP_Query($args);
  if ($products->have_posts()) :
      $i=0;
      while ($products->have_posts()) : $products->the_post();
          $autor = get_field('autor');
          if($i % 2 ==0) ?>


                    <h3><?php the_title();?></h3>

  <?php  if ($i % 2 != 0)
  $i++;
  endwhile;endif;?>

It doesn’t show any title, if I remove the meta_query it shows all products so the problem is that the relation meta_query code is not working. Any ideas how to use it on WooCommerce template?

Related posts

2 comments

  1. You use get_the_ID() to get the author id in meta_query args.

    get_the_ID() – will get the Post id, not the author id.

    To get all posts by authoк id your args should look like this:

    $args = array(
            'author' => 1,
            'post_type' => 'product',
            'posts_per_page' => 8,
    );
    

    I also see that you using get_field()-function. WordPress core does not have this function. You can use instead get_the_author().

    Eventually your code will look like:

    <?php
    $args = array(
            'author' => 1,
            'post_type' => 'product',
            'posts_per_page' => 8,
    );
    $products = new WP_Query($args);
    
    if ($products->have_posts()) :
            $i=0;
            while ($products->have_posts()) : $products->the_post();
                    $autor = get_the_author();
                    if($i % 2 ==0) ?>
                                        <h3><?php the_title();?></h3>
    
    <?php  if ($i % 2 != 0)
    $i++;
    endwhile;endif;?>
    
  2. You can use this code snippet for meta_query in woocommerce
    
    $args = array(
        'post_type'     => 'product',
        'post_status'   => 'publish',
        'posts_per_page'=> 10,
        'orderby'       => 'total_sales',
        'order'         => 'DESC',
        'meta_query'    => array(
            'relation'  => 'OR',
            array(
                'key'       => '_featured',
                'value'     => 'yes',
                'compare'   => '='
            ),
            array(
                'key'       => 'total_sales',
                'value'     => '10',
                'compare'   => '>='
            )
        )
    );
    $query = new WP_Query( $args );
    

Comments are closed.