Display related products by matching the product title to any tags of the current article

272 Views Asked by At

How do I display products in a custom post type single page by matching the queried product title to any tags of the current article?

Below is my code which seems to output some random product names, but it should only be returning one product (at the moment) where product title is also a tag in the current post... with me?

            <?php 

            // Query products related to current article

            $current_article_tags = get_the_tags();

            $related_products = new WP_Query(array(
              'post_type'=> 'product',
              'title'    => $current_article_tags
            ));


            while(  $related_products->have_posts()){
                $related_products->the_post(); 

                // Get products number
                $related_product_count = $related_products->post_count;

                //echo '<pre>'; print_r($related_products->posts); echo '</pre>';
                echo $related_products->post->post_title; 

                ?>

            <?php
            }
            wp_reset_postdata();
            ?>
1

There are 1 best solutions below

0
Djave On

First of all, you need to query by an array of values:

MySQL Like multiple values

WHERE interests LIKE '%sports%' OR interests LIKE '%pub%'

In your case, we can probably make that structure quite nicely using array_map and maybe strtolower (get_the_tags returns an array of terms, we need them to look like the above)

$current_article_tags = get_the_tags();
$tags_for_query = array_map(function($term){
  // Post title 1 ==> '%post title 1%'
  return "'%" . strtolower($term->name) . "%'";
}, $current_article_tags)

Now we should have an array like this

[
  '%post title 1%',
  '%post title 2%'
]

We need to join them into a string, or implode them in php language

$sql = "WHERE post_title LIKE " . implode(" OR post_title LIKE ", $tags_for_query);

$sql should now output something like...

WHERE post_title LIKE '%post title 1%' OR post_title LIKE  '%post title 2%' 

I hope this gets you started.