相关产品分类wordpress

时间:2017-08-18 11:27:22

标签: php wordpress

我有问题,我无法获得该类别中的相关产品,谁能说出来?

<?php
    global $post;
    $args = array(
        'post_type' => 'twin_posts',
        'showposts' => 4
    );
    $categories = get_the_category( $args );
    $old_query = $wp_query;
    $wp_query = new WP_Query( $args );
?>
<ul class="ps-list row">
<?php
    while ( have_posts() ) : the_post();
    endwhile;
    $wp_query = $old_query;
?>
</ul>

1 个答案:

答案 0 :(得分:0)

首先,您必须获取当前产品的类别ID。

global $post;

$terms = get_the_terms( $post->ID, 'product_cat' );

$product_cat_id = array();

foreach ($terms as $term) {
    $product_cat_id[] = $term->term_id;

}

然后在WP_Query代码下面使用它:

$args = array(
    'post_type'             => 'product',
    'post_status'           => 'publish',
    'ignore_sticky_posts'   => 1,
    'posts_per_page'        => '12',
    'meta_query'            => array(
        array(
            'key'           => '_visibility',
            'value'         => array('catalog', 'visible'),
            'compare'       => 'IN'
        )
    ),
    'tax_query'             => array(
        array(
            'taxonomy'      => 'product_cat',
            'field' => 'term_id', //This is optional, as it defaults to 'term_id'
            'terms'         => $product_cat_id,
            'operator'      => 'IN' // Possible values are 'IN', 'NOT IN', 'AND'.
        )
    )
);
$products = new WP_Query($args);