2017-08-18 96 views
-1

我有問題,我無法獲取該類別的相關產品,誰能告訴?相關產品按類別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> 

回答

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