Created
October 1, 2018 15:40
-
-
Save sterndata/ba90392362f70a11bbaa6ba6576d4744 to your computer and use it in GitHub Desktop.
get related products by taxonomy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function related_product_id_by_tax( $id, $tax ) { | |
$transient_name = 'related_' . $id . '_' . $tax; | |
$transient_time = 60 * 60 * 12; // 12 hours | |
if ( false === ( $transient_results = get_transient( $transient_name ) ) ) { | |
$tags_array = array(); | |
$tags = wp_get_post_terms( $id, $tax ); | |
foreach ( $tags as $tag ) { | |
$tags_array[] .= $tag->term_id; | |
} | |
$args = array( | |
'post_type' => 'product', | |
'post__not_in' => array( $id ), | |
'posts_per_page' => 3, | |
'fields' => 'ids', | |
'orderby' => 'rand', | |
'tax_query' => array( | |
array( | |
'taxonomy' => $tax, | |
'field' => 'id', | |
'terms' => $tags_array, | |
'operator' => 'IN', | |
), | |
), | |
); | |
$query = new WP_Query( $args ); | |
set_transient( $transient_name, $query->posts, $transient_time ); | |
return $query->posts; | |
} else { | |
return $transient_results; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment