wordpress 在Woocommerce中获取与产品类别相关的所有属性及其术语

2izufjch  于 2023-08-03  发布在  WordPress
关注(0)|答案(2)|浏览(103)

如我们所知,要将特定属性的术语添加到产品中,我们可以用途:

$attr_terms = $product->get_attribute( 'attr_slug' );

字符串
或获取特定属性的所有术语,而不管我们可以使用的产品

$attr_terms = get_terms( 'pa_attr_slug' );


但如何将所有属性与其条款添加到特定产品类别的产品中?
类似于:

$cat_attrs = ... ($cat->id);

foreach($cat_attrs as $cat_attr) {

    echo $cat_attr->name; // name of attribute

    foreach($cat_attr->terms as $term) {
        echo $term->name; // name of attribute term
    }
}

svgewumm

svgewumm1#

要获取与产品类别相关的产品属性分类/术语名称数组,请尝试以下操作:

// Here define the product category SLUG
$category_slug = 'posters';

$query_args = array(
    'status'    => 'publish',
    'limit'     => -1,
    'category'  => array( $category_slug ),
);

$data = array();
foreach( wc_get_products($query_args) as $product ){
    foreach( $product->get_attributes() as $taxonomy => $attribute ){
        $attribute_name = wc_attribute_label( $taxonomy ); // Attribute name
        // Or: $attribute_name = get_taxonomy( $taxonomy )->labels->singular_name;
        foreach ( $attribute->get_terms() as $term ){
            $data[$taxonomy][$term->term_id] = $term->name;
            // Or with the product attribute label name instead:
            // $data[$attribute_name][$term->term_id] = $term->name;
        }
    }
}

// Raw output (testing)
echo '<pre>'; print_r($data); echo '</pre>';

字符串
你会得到类似的东西(一个示例摘录):

Array
(
    [pa_color] => Array
        (
            [9]  => Blue
            [10] => Green
        )
    [pa_size] => Array
        (
            [15] => Small
            [16] => Medium
            [18] => Large
        )
)

dfddblmv

dfddblmv2#

我们首先使用了公认的方法,但在产品类别有数百个产品的情况下,它达到了内存限制。为了优化它,我们将其转换为原始查询。
希望这能派上用场:)

global $wpdb;

$attributes_query = $wpdb->prepare(
    "SELECT tr.object_id, tt.taxonomy, tt.term_id, t.name
    FROM {$wpdb->prefix}term_relationships AS tr
    JOIN {$wpdb->prefix}term_taxonomy AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
    JOIN {$wpdb->prefix}terms AS t ON tt.term_id = t.term_id
    WHERE tr.object_id IN (
        SELECT p.ID
        FROM {$wpdb->prefix}posts AS p
        JOIN {$wpdb->prefix}term_relationships AS tr ON p.ID = tr.object_id
        JOIN {$wpdb->prefix}term_taxonomy AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
        JOIN {$wpdb->prefix}terms AS t ON tt.term_id = t.term_id
        WHERE p.post_type = 'product'
        AND p.post_status = 'publish'
        AND tt.taxonomy = 'product_cat'
        AND t.slug = '{$args['category']}'
    )
    AND tt.taxonomy LIKE %s",
    'pa_%'
);

$results = $wpdb->get_results($attributes_query);

字符串

相关问题