我的网站上有32个类别和1000个产品。.但是我的客户想要添加一个“所有产品”类别,并且他希望在此类别中显示所有产品,因此当用户单击此类别时,所有产品都会显示
i have try this like get product category and them get the all prodcut category term_id and then use the
wp_set_object_terms( $product_id, $term_ids, 'product_cat' );
but does not work
this is the code
$product_id = 5558;
$term_ids = [ 130, 12, 18 ];
wp_set_object_terms( $product_id, $term_ids, 'product_cat' );
no error that code is not add that category to this product
答案 0 :(得分:0)
您可以尝试
<?php
//Get all Terms
$args_cat = array(
'taxonomy' => "product_cat",
'hide_empty' => false,
);
$product_categories = get_terms( $args_cat );
$term_ids = array();
foreach ( $product_categories as $product_categories_key => $product_categories_value ) {
$term_ids[] = $product_categories_value->term_id;
}
//Get all Products
$args_product = array(
'post_type' => 'product',
'posts_per_page' => -1,
);
$loop_product = new WP_Query( $args_product );
while ( $loop_product->have_posts() ) : $loop_product->the_post();
global $product;
$id = $product->get_id();
wp_set_object_terms( $id, $term_ids, 'product_cat' );
echo get_the_title();
endwhile;
wp_reset_query();