php - 单一产品页面 - 从相关产品中排除当前产品

标签 php wordpress woocommerce categories product

这是关于 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);
?>

但我试图阻止当前产品显示在相关产品上。我尝试使用下面代码的第一秒,但它没有排除,而是检索所有默认帖子。

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

我怎样才能实现这个目标?

谢谢

最佳答案

根据您的第一个代码片段,这应该可行,并且将避免在基于当前产品类别的相关产品中显示您当前的产品。

这是代码:

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

?>

这应该有效......

关于php - 单一产品页面 - 从相关产品中排除当前产品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38932196/

相关文章:

javascript - 访问不存在的图像 URL 是否会影响 Web 服务器?

php - 如何解决 WordPress 嵌套子类别存档页面的 url 问题

php - WooCommerce 中一件免费产品的数量折扣

php - 向 WooCommerce 中的特定产品添加额外的添加到购物车按钮

php - 如何使用 PHP 将阿拉伯字符转换为 Unicode

php - 查询返回 3 行的相同数据

wordpress - 隐藏 WordPress 仪表板?

php - 将 WooCommerce 自定义 session 变量保存为订单元数据

localhost 中的 php pdo 更新查询在服务器 centOS 中不起作用

php - MySQL 服务器版本与 PHP 报告的 MySQL 版本不同