2016-08-13 8 views
2

これは、WooCommerceの単一の製品ページについてです。関連商品を表示するために商品カテゴリを使用しようとしています。私は以下のコードでそれを表示することができます。これを使用すると現在の投稿が表示され、商品のみが表示されます。単一の製品ページ - 関連製品からの現在の製品を除外

<?php 
    global $post; 
     $terms = get_the_terms($post->ID, 'product_cat');  
     foreach ($terms as $term ) {   
      $product_cat_name = $term->name; 
      break; 
     }   
    $ids = array(); 

    $currentID = get_the_ID(); 

    $args = array('post_type' => 'product', 'product_cat' => $product_cat_name);  
    $loop = new WP_Query($args); 
    while ($loop->have_posts()) : $loop->the_post(); global $product; 
     $ids[] = $loop->post->ID; 
    endwhile; 
    wp_reset_query(); 

    print_r($ids); 
?> 

しかし、私は現在の製品がその関連製品に表示されないようにしようとしています。私は以下のコードの最初の2分の1を使用しようとしましたが、除外するのではなく、すべてのデフォルト投稿を取得します。

<?php 
    global $post; 
     $terms = get_the_terms($post->ID, 'product_cat');  
     foreach ($terms as $term ) {   
      $product_cat_name = $term->name; 
      break; 
     }   
    $ids = array();  

    $currentID = get_the_ID(); 

    $args = array('post_type' => 'product', 'product_cat' => $product_cat_name, 'post__not_in' => array($currentID));  
    $loop = new WP_Query($args); 
    while ($loop->have_posts()) : $loop->the_post(); global $product; 
     $ids[] = $loop->post->ID; 
    endwhile; 
    wp_reset_query(); 

    print_r($ids); 
?> 

どうすればこの問題を解決できますか?

おかげ

+0

[OK]を私はあなたが...それが動作するはずのための機能的な答えを持っています。私は自分のコードglobal $ productを削除しました。ここでは不要です。それを試して教えてください。 – LoicTheAztec

答えて

1

はあなたの最初のコードスニペットに基づいて、この作業をする必要がありますし、現在の製品カテゴリに基づいて関連製品であなたの現在の製品を表示するために避けることができます。

これはコードです:

<?php 

global $post; 

$ids = array(); 

// Get the "main" product category 
$terms = get_the_terms($post->ID, 'product_cat'); 
foreach ($terms as $term){ 
    if($term->parent != 0) { 
     $product_cat_name = $term->name; 
     break; // stop the loop 
    } 
// The Query  
$loop = new WP_Query(array(
    'post_type' => 'product', 
    'product_cat' => $product_cat_name, 
    'post__not_in' => array($post->ID) // Avoid displaying current product 
)); 

if ($loop->have_posts()): 
    while ($loop->have_posts()) : $loop->the_post(); 
     $ids[] = $loop->post->ID; // Set all other product IDs for that product category 
    endwhile; 
endif; 

wp_reset_query(); 

// Raw output 
print_r($ids); 

?> 

これは動作するはずです...

+0

これは私のために働かなかった。 :/それは最新のwoocommerceをエラーします。 – GauchoCode

+0

@GauchoCode ...私はテストし、更新し、私の回答コードを最適化しました。あなたが好きならそれを試してみてください。ありがとう(と申し訳ありません...ブラケットのエラーがありませんでした) – LoicTheAztec

関連する問題