2

我想在某些产品类别中为 woocommerce 产品设置属性。但是,该查询似乎不起作用。

我已将以下代码放入我的子主题的functions.php 中。尝试用 term_id 替换 slug,尝试添加“关系”,以防万一,尝试显式设置 slug 而不是变量,但仍然没有运气。UPD:wc_get_products 和 WC_Product_Query 也不起作用。

function wccategory_set_attributes($categoryslug, $attributes) {
    $pquery = new WP_Query( array(
        'post_type'   => 'product',
        'post_status' => 'publish',
        'posts_per_page' => 10,
        'tax_query'   => array(
            array(
                'taxonomy' => 'product_cat',
                'field'    => 'slug',
                'terms'    => $categoryslug,
            ),
        ),
    ));

    if( $pquery->have_posts() ) {
        while ($pquery->have_posts()) : $pquery->the_post();
            foreach ($attributes as $name => $value) {
                wp_set_object_terms( $postid, $value, $name, false );
                $product_attributes[$i] = array (
                    'name' => htmlspecialchars( stripslashes( $name ) ),
                    'value' => $value,
                    'is_visible' => 1,
                    'is_taxonomy' => 0
                );
                $i++;
            }
            update_post_meta( $postid,'_product_attributes', $product_attributes); 
        endwhile;
    }
}
wccategory_set_attributes('theslug', array ( 'pa_length' => '', 'pa_width' => '', 'pa_type' => ''));

$pquery->have_posts() 什么也不返回。不过,这些帖子是存在的。从参数中删除“tax_query”后,一切正常。我假设“tax_query”中有一些错误。我看了很多其他的例子,看起来不错,但似乎我错过了一些东西。

4

1 回答 1

0

您是否尝试过使用 get_posts() 代替?如果您只是尝试检索帖子计数,则可能不需要完整的查询,并且 get_posts 会自行返回一个数组。

此外,与其尝试在函数之外使用返回的项目,如果您返回的唯一内容是帖子计数,那么只返回计数?最后,post_count 与 found_posts 不同。如果您每页设置一个帖子,您的 post_count 将始终达到该数量的最大值,found_posts 将提供在该查询中找到的所有帖子。

 function get_cat_products_by_slug($category) {

  $products = get_posts(
     array(
       'posts_per_page' => -1,
       'post_type' => 'product',
       'tax_query' => array(
         array(
            'taxonomy' => 'product_cat',
            'field' => 'slug',
            'terms' => $category->slug,
           )
       )
    )
 );

 $number_of_posts = $products->found_posts;

 return $number_of_posts;

};

$p_query = get_cat_products_by_slug($category);
echo $p_query;
于 2019-06-11T21:58:39.173 回答