星期四 , 17 4 月 2025

product related posts


<?php
// Get the current product's ID
$current_product_id = get_the_ID();

// Get the terms (categories/tags) of the current product
$terms = get_the_terms($current_product_id, 'product_category'); // Replace with your taxonomy

if ($terms && !is_wp_error($terms)) {
    $term_ids = array();
    
    // Get all term IDs
    foreach ($terms as $term) {
        $term_ids[] = $term->term_id;
    }
    
    // Setup the related products query
    $args = array(
        'post_type' => 'product', // Your custom post type
        'posts_per_page' => 4, // Number of related products to display
        'post__not_in' => array($current_product_id), // Exclude current product
        'tax_query' => array(
            array(
                'taxonomy' => 'product_category', // Replace with your taxonomy
                'field' => 'term_id',
                'terms' => $term_ids,
                'operator' => 'IN'
            )
        )
    );
    
    // Run the query
    $related_products = new WP_Query($args);
    
    // Check if related products exist
    if ($related_products->have_posts()) : ?>
        <div class="related-products">
            <h3>Related Products</h3>
            <div class="products-grid">
                <?php while ($related_products->have_posts()) : $related_products->the_post(); ?>
                    <div class="product-item">
                        <a href="<?php the_permalink(); ?>">
                            <?php if (has_post_thumbnail()) : ?>
                                <?php the_post_thumbnail('medium'); ?>
                            <?php endif; ?>
                            <h4><?php the_title(); ?></h4>
                        </a>
                        <div class="product-excerpt">
                            <?php the_excerpt(); ?>
                        </div>
                        <a href="<?php the_permalink(); ?>" class="view-product">View Product</a>
                    </div>
                <?php endwhile; ?>
            </div>
        </div>
    <?php endif;
    
    // Reset post data
    wp_reset_postdata();
}
?>