首页 > 解决方案 > 根据类别显示随机产品

问题描述

我在一个产品的单个产品页面中。我想展示,在这个产品之后,其他 4 个同类别的随机产品

我只有这个:(PHP)

<?php
        global $product;
        $terms = get_the_terms( $product->get_id(), 'product_cat' );

        var_dump($terms);
    $args = array(
        'posts_per_page'   => 4,
        'orderby'          => 'rand',
                'post_type'        => 'product' ); 

    $random_products = get_posts( $args );

    foreach ( $random_products as $post ) : setup_postdata( $post ); ?>
    <li>
        <a href="<?php the_permalink(); ?>">
    <?php the_title(); ?></a>
    </li>
<?php endforeach; 
wp_reset_postdata();
?>

谁能帮我?谢谢

标签: phphtmlwordpresswoocommerce

解决方案


你可以试试这个方法。我检查了它的工作:

global $product;
    $terms = get_the_terms( $product->get_id(), 'product_cat' );
    $first_term = array_shift( $terms );

    $args = array(
        'posts_per_page'   => 4,
        'orderby'          => 'rand',
        'post_type'        => 'product',
        'tax_query' => array(
            array(
                'taxonomy' => 'product_cat',
                'field'    => 'slug',
                'terms'    => array( $first_term->slug )
            )
        ),
        'post__not_in' => array( $product->get_id() )
    );

    $random_products = get_posts( $args );

    foreach ( $random_products as $post ) : setup_postdata( $post ); ?>
        <li>
            <a href="<?php the_permalink(); ?>">
                <?php the_title(); ?></a>
        </li>
    <?php endforeach;
    wp_reset_postdata();
    ?>

推荐阅读