Ask your WordPress questions! Pay money and get answers fast! (more info)

Show related products by category and tag WordPress

  • SOLVED

Thanks in advance for all help

I'm using Woocommerce and would like to show related products from a defined category & tag. The tag name is fetched from the current product which is defined in a custom field.


<?php
$product_id = get_post_meta($post->ID, "product_id", true);
$args = array('post_type' => 'product', 'product_cat' => 'category_name', 'product_tag' => '$product_id');
$postslist = get_posts( $args );
foreach ($postslist as $post) : setup_postdata($post); ?>
<ul>
<li><?php the_title(); ?></li>
</ul>
<?php endforeach; ?>



I would really appreciate some help here as I'm not getting it to work.

Answers (1)

2013-02-09

Arnav Joy answers:

try this

<?php
//for use in the loop, list 5 post titles related to first tag on current product
$product_id = get_post_meta($post->ID, "product_id", true);
$tags = wp_get_post_tags($product_id);
if ($tags) {
echo 'Related Product';
$first_tag = $tags[0]->term_id;
$args=array(
'tag__in' => array($first_tag),
'post__not_in' => array($product_id),
'showposts'=>5,
'caller_get_posts'=>1
);
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
<?php
endwhile;
}
}
?>


peace153 comments:

Arnav, thanks for your quick reply. Just tested your code and it is not working for me.

My code is actually working fine for me, except that I would like to define the "product_tag" via a custom field of the current product post.


<?php

$args = array('post_type' => 'product', 'product_cat' => 'canvas', 'product_tag' => 'h1');

$postslist = get_posts( $args );

foreach ($postslist as $post) : setup_postdata($post); ?>

<ul>
<li><?php the_title(); ?></li>
</ul>

<?php endforeach; ?>


Arnav Joy comments:

so you can do following , create a custom field "product_tag"and then use following


<?php

$product_tag = get_post_meta($post->ID, "product_tag", true);

$args = array('post_type' => 'product', 'product_cat' => 'canvas', 'product_tag' => $product_tag );



$postslist = get_posts( $args );



foreach ($postslist as $post) : setup_postdata($post); ?>



<ul>

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

</ul>



<?php endforeach; ?>


peace153 comments:

Arnav, thanks so much. You made my day :-) I was hoping so much to work this out within the next couple of hours. The code works.

Have a nice day.