Dynamic variable for custom taxonomy in loop?

I have a custom page template that loops through all custom posts with the post_type of “product_listing” AND the custom taxonomy “product_cat” of “shirts” and returns 4 posts per page (as seen below:)

<?php $loop = new WP_Query( array( 'post_type' => 'product_listing', 'product_cat' => 'shirts', 'posts_per_page' => 4 ) ); ?>

It is the client’s responsibility to manage those categories. I’d like to assign a variable to display in place of “shirts” so that I don’t have to modify the template each time the client adds a new product category (such as shoes, pants, etc.).

Read More

I am not a programmer by any means. Does anybody have a snippet of code that would work for this? Or perhaps an article I could read more about assigning dynamic variables in the loop? Thanks!

Related posts

Leave a Reply

2 comments

  1. You could let your client add the product category via a custom field.

    <?php $loop = new WP_Query( array( 'post_type' => 'product_listing', 'product_cat' => get_post_meta($post->ID, 'product_cat', true), 'posts_per_page' => 4 ) ); ?>
    

    This should work if your client adds a custom field value for the key ‘product_cat’.

  2. Apparently I needed to loop the function to set the variable:

    <!-- BEGIN CODE FOR PRODUCT AREA -->
       <?php $prod_cats = get_terms('product_cat');
       foreach ($prod_cats as $prod_cat) {
          $cat_name = $prod_cat->name; ?>
            <div id="products">
            <!-- post begin -->
            <?php $loop = new WP_Query( array( 'post_type' => 'product_listing', 'posts_per_page' => 4, 'product_cat' => $cat_name ) ); ?>
            <?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
            <div class="product-tease" id="post-<?php the_ID(); ?>">
                <div class="upper">
                    <h3><a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></h3>
                    <p align="center"><a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><img src="<?php echo catch_that_image() ?>" /></a></p>
                    <?php the_excerpt('Read the rest of this entry &raquo;'); ?>
                </div>
                <span class="btn-readon"><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>">Read On</a></span>
                </div>
            <?php endwhile; ?>
            <br clear="all" />
            <!-- post end -->
            <br clear="all" />
              <?php wp_reset_query(); ?>
              <?php rewind_posts(); ?>
            </div>
       <?php } // End foreach $prod_cats ?>