Skip to content

Instantly share code, notes, and snippets.

@alexdeborba
Last active June 8, 2023 11:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexdeborba/167a09d7e766cc1621d01b47b348139b to your computer and use it in GitHub Desktop.
Save alexdeborba/167a09d7e766cc1621d01b47b348139b to your computer and use it in GitHub Desktop.
Action to show on Single Product only Related Products to Product Archive
// Remove default related products function
remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_related_products', 20 );
// Add our custom related products function to the same hook
add_action( 'woocommerce_after_single_product_summary', 'custom_related_products', 20 );
function custom_related_products() {
// Use global $product object
global $product;
// Prepare the arguments for WP_Query
$args = array(
'post_type' => 'product', // Only get products
'posts_per_page' => 4, // Number of related products to show
'ignore_sticky_posts' => 1, // Ignore sticky posts
'no_found_rows' => 1, // Optimizes WP_Query when pagination is not needed
'post__not_in' => array( $product->get_id() ), // Exclude the current product
'tax_query' => array(
array(
'taxonomy' => 'product_cat', // We're using product categories
'field' => 'id', // We're referencing the categories by ID
'terms' => wp_get_post_terms( $product->get_id(), 'product_cat', array( 'fields' => 'ids' ) ), // Get IDs of categories of current product
)
)
);
// Query related products
$related_products = new WP_Query( $args );
// Check if the query found any related products
if( $related_products->have_posts() ) {
// Output section and header
echo '<section class="related products">';
echo '<h2>' . __( 'Related Products', 'woocommerce' ) . '</h2>';
echo '<ul class="products columns-4">';
// Loop through related products
while ( $related_products->have_posts() ) {
$related_products->the_post();
// Get the product content template for each related product
wc_get_template_part( 'content', 'product' );
}
// Close section
echo '</ul>';
echo '</section>';
}
// Restore original Post Data
wp_reset_postdata();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment