为了账号安全,请及时绑定邮箱和手机立即绑定

根据类别显示随机产品

根据类别显示随机产品

PHP
慕标5832272 2023-10-21 19:58:14
我在产品的单个产品页面中。我想在该产品之后展示 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();?>谁能帮我?谢谢
查看完整描述

1 回答

?
青春有我

TA贡献1784条经验 获得超8个赞

你可以试试这个方法。我检查了它是否有效:


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();

    ?>


查看完整回答
反对 回复 2023-10-21
  • 1 回答
  • 0 关注
  • 67 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信