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();
?>
First of all, you need to query by an array of values:
MySQL Like multiple values
In your case, we can probably make that structure quite nicely using
array_mapand maybestrtolower(get_the_tagsreturns an array of terms, we need them to look like the above)Now we should have an array like this
We need to join them into a string, or
implodethem in php language$sqlshould now output something like...I hope this gets you started.