1
votes

I have a products post type and it has a various categories. Currently there are around fifty plus posts assigned to different categories. Note: I am using a custom taxonomy called product_categories.

Scenario:

  1. I have a category named food-products and it has a sub categories as chocolates, dairy, grocery.
  2. Now when user goes to the category page eg site.com/product-category/food-products at that time all other categories posts are also displaying but when i click on the sub category tabbing menu at that time it displays the correct assigned sub category posts

So, my question is how can the only the respected category of subcategory posts will be displayed on page load ?

<?php $loop = new WP_Query(array('post_type' => 'product', 'posts_per_page' => -1));
$count =0; ?>        
<div class="row portfolio-container">
<?php if ( $loop ) : while ( $loop->have_posts() ) : $loop->the_post(); 
  $url = get_the_post_thumbnail_url( $post_id, 'thumbnail_size' );
  $terms = get_the_terms( $post->ID, 'product_categories' );
  if ( $terms && ! is_wp_error( $terms ) ) : 
    $links = array();
    foreach ( $terms as $term )  { $links[] = $term->name; }
      $links = str_replace(' ', '-', $links); 
      $tax = join( " ", $links );     
  else :  
    $tax = '';  
  endif; ?>      
  <div class="col-lg-4 col-md-6 portfolio-item <?php echo strtolower($tax); ?>">
    <div class="portfolio-wrap">
      <img src="<?php echo $url;?>" class="img-fluid" alt="">
      <div class="portfolio-info">
        <h4><a href="<?php the_permalink() ?>"><?php the_title();?></a></h4>
        <div class="portfolio-links">
          <a href="<?php echo $url; ?>" data-lightbox="portfolio" data-title="App 1" class="link-preview" title="Preview"><i class="ion ion-eye"></i></a>
          <a href="<?php the_permalink() ?>" class="link-details" title="More Details"><i class="ion ion-android-open"></i></a>
        </div>
      </div>
    </div>
  </div>
  <?php endwhile;?>
  <?php wp_reset_query();?>
  <?php endif;?>
</div>

JQuery:

$(window).on('load', function () {
  var portfolioIsotope = $('.portfolio-container').isotope({
    itemSelector: '.portfolio-item'
  });
  $('#portfolio-flters li').on( 'click', function() {
    $("#portfolio-flters li").removeClass('filter-active');
    $(this).addClass('filter-active');
    portfolioIsotope.isotope({ filter: $(this).data('filter') });
  });
});

Here is my working demo video for review.

1
I'm not clear what exactly the problem is... do you want it to show products from just one category on page load? IThat is to do with the filter, not the php. Or do you mean that it is showing posts that are not in the categories you want?FluffyKitten
I have a category named food-products and it has a sub categories as chocolates, dairy, grocery. Now when user goes to the category page eg site.com/product-category/food-products at that time all other categories posts are also displaying but when i click on the sub category tabbing menu at that time it displays the correct assigned sub category posts.... So, my question is how can the only the respected category of subcategory posts will be displayed on page load ?TMA
I understand now, thanks. It might be a good idea to edit your question to include this extra information so that it might help to other people with similar problems I've posted an answer below, hope that helps!FluffyKitten
Okay sir, let me update my question and let i try your solution.TMA
"a magician of the WordPress"...I like that! Maybe I'll make that my screen name :D Glad to help, I don't mind spending time with someone like you who genuinely wants to learn & to help others here too. And now you have more knowledge to help out other users :) "Pay it forward" and keep up the good work!FluffyKitten

1 Answers

1
votes

Your WP_Query is returning all products, so that is why they are all getting shown on page load. You need to change the query so it only gets the ones in the category/categories you want.

You want to get products in a certain category, e.g. food-products and all it's sub categories, (e.g. chocolates).

To do this, you can change your WP_Query to specify the category to use like this :

$loop = new WP_Query(
               array('post_type' => 'product', 
                     'posts_per_page' => -1, 
                      array( 'category_name' => 'food-products' ) // <-- THIS!! Also note that it is in an array
               ));

This tells WP_Query to get all product posts that belong to the food-products category, so it will return any products with the food-products category as well as any products in any of the child categories, e.g. chocolates

WP_Query has a number of different ways you can query by category... take a look at the category section of the WP_Query documentation for more information.


UPDATE: Custom Taxonomies

You can do the same thing for custom taxonomies, but you need to use tax_query in the arguments instead of category_name. Your WP_Query should be something like this:

// you don't need to create a variable for the args, if just makes it clearer in the example
$args = array (
    'post_type' => 'product', 
    'posts_per_page' => -1, 
    'tax_query' => array(
        array(                            // note the nested arrays
              'taxonomy' => 'product_categories',  // this is the name of your custom taxonomy
              'field' => 'slug',          // you can search by slug, name, term_id or term_taxonomy_id
              'terms' => 'food-products'  // the taxonomy slug to search for
        )
    )
);

$loop = new WP_Query($args);

You might need to change the values for taxonomy and term to match your custom taxonomy. I've also assumed you are searching by slug, but you can search by name or id either.

There is an include_children parameter for the tax_query that you use to say whether or not to include children (e.g. chocolates) in the results, but this defaults to true so you only need to use it if you don't want to include children.

Here's the taxonomy section of the WP_Query documentation for more information.


UPDATE 2: Getting the products for the current category

You say in the comments that you have one template for all of the terms taxonomy-product_categories.php, each category shows in its own page using this template but you only want to show the products with the current term.

What you need to do is use just the current term in the WP_Query, not all of them. You should be able to use get_queried_object() to get the current term and use it in your tax_query instead of hard coding the specific terms.

// get the term of the current page
// We can then use $currentterm->slug in tax_query to dynamically search for this term instead of hard coding a specific term
$currentterm = get_queried_object();

$args = array (
    'post_type' => 'product', 
    'posts_per_page' => -1, 
    'tax_query' => array(
        array(                            // note the nested arrays
              'taxonomy' => 'product_categories',  // this is the name of your custom taxonomy
              'field' => 'slug',          // you can search by slug, name, term_id or term_taxonomy_id
              'terms' => $currentterm->slug  // search for the slug of the current term
        )
    )
);
$loop = new WP_Query($args);

So what this should do is: if you are on e.g. site.com/product-category/food-products, it will get the current term which is food-products and then only search for products with that category. When you go to e.g. site.com/product-category/home-decor, it will dynamically pick up the new term as home-decor and use it in the query.