I have products with two categories assigned I selected the primary category on each products under category selection. Now I want to show related products by primary products.
I am using the yoast seo plugin.
I added the below filter code in the child theme's function.php file, but it's not working.
// Alter related products query to pull items from Yoast Primary Category
add_filter( 'woocommerce_get_related_product_cat_terms', function( $terms, $product_id ) {
if ( function_exists( 'yoast_get_primary_term_id' ) ) {
$primary_term_product_id = yoast_get_primary_term_id( 'product_cat', $product_id );
if ( $primary_term_product_id ) {
return array( $primary_term_product_id );
}
}
return $terms;
}, 10, 2 );
The filter should be okay, problem is that related products in Wordpress are cached in database using transients.
The transients can be found in wp_options table with names _transient_wc_related_[product_id]
and _transient_timeout_wc_related_[product_id]
.
In order to see the filter effect immediately you need to delete these from your database.
Following SQL query should do the deletion:
DELETE FROM wp_options WHERE option_name REGEXP '^_transient_timeout_wc_related_[0-9]*$|^_transient_wc_related_[0-9]*$'
After the deletion, wordpress will recreate new transients with updated data.
More info about Wordpress transients:
https://developer.wordpress.org/apis/handbook/transients/