让这个Wooccommerce短代码只显示某些类别



我找到了这个函数片段,并将其插入到我的网站中。到目前为止效果很好,但我需要做一个小改动:我怎么能让函数只显示某个类别。。。?

这是代码:

add_shortcode( 'my_purchased_products', 'products_bought_by_curr_user' );

function products_bought_by_curr_user() {

$current_user = wp_get_current_user();
if ( 0 == $current_user->ID ) return;

$customer_orders = get_posts( array(
'numberposts' => -1,
'meta_key'    => '_customer_user',
'meta_value'  => $current_user->ID,
'post_type'   => wc_get_order_types(),
'post_status' => array_keys( wc_get_is_paid_statuses() ),
) );

if ( ! $customer_orders ) return;
$product_ids = array();
foreach ( $customer_orders as $customer_order ) {
$order = wc_get_order( $customer_order->ID );
$items = $order->get_items();
foreach ( $items as $item ) {
$product_id = $item->get_product_id();
$product_ids[] = $product_id;
}
}
$product_ids = array_unique( $product_ids );
$product_ids_str = implode( ",", $product_ids );

return do_shortcode("[products ids='$product_ids_str']");

}

有人能把我推向正确的方向吗

致以最良好的问候Andi

我误解了你的问题,所以现在是编辑时间了。您将无法在get_posts((上筛选类别,因为您获得的是订单而不是产品(这就是我的解决方案不起作用的原因(。

为了实现你的过滤,你需要在这部分工作:

foreach ( $items as $item ) {
$product_id = $item->get_product_id();
$product_ids[] = $product_id;
}

通过检查产品是否包含您希望从中获取产品的类别。像这样的东西应该起作用:

foreach ( $items as $item ) {
$product_id = $item->get_product_id();
$terms = get_the_terms( $product_id, 'product_cat' );

foreach ( $terms as $term ) {
if($term->slug === 'the_category_slug') {
$products_ids[] = $product_id;
}
}
}

我使用了这篇文章中的代码。如何在WooCommerce结账时从订单中获得类别?

因此,这里发生的事情是,在获得product_id之后,我们使用get_terms获得产品类别("product_cat"参数是只获取产品类别,而不获取带有它的产品标签,因为类别和标签都是术语(。

在得到这个术语后,我们循环到它中,并检查每个术语是否是我们想要得到的类别(。如果是,我们将产品id推送到结果数组。

我们在这里使用类别段塞,但我们可以通过替换来使用ID

if($term->slug === 'the_category_slug')

通过

if($term->term_id === 149)

其中149是您想要的类别的ID

如果你需要更多的帮助和好运,请告诉我

您可以通过产品ID获取产品类别。现在,您可以使用if条件进行检查。

如果类别id是X,那么job也是。

要响应新的崩溃问题:

我建议您激活WordPress调试(如果网站崩溃,它会在屏幕上显示PHP错误(。您可以编辑项目根目录(项目的顶级文件夹(中的wp-config.php文件,并在其中放入以下行:

define( 'WP_DEBUG', true ); 

(你可以把它放在任何地方(。然后你应该知道你的网站崩溃的原因。

我还没有时间测试代码,但我看到的是你忘记了$和;线上的字符

products_ids[] = $product_id

应该变成

$products_ids[] = $product_id;

如果您在屏幕上看到错误,请返回并将其张贴在此处:(

最新更新