1

我已经阅读了有关基于帖子标签分配类别的其他答案。但这可以基于postmeta来完成吗?

我假设可以,并且我一直在尝试更改以下代码段(在另一个答案中引用)以实现此目的。但是我没有运气调整它以引用 postmeta meta_key(delivery_option)和 meta_value(pick-up、postal、post & parcel),然后自动分配一个类别(pick-up、postal 或 post & parcel)。

如果相关,上面的 postmeta 键和值已由另一个插件添加。

function auto_add_category ($product_id = 0) {
if (!$product_id) return;

// because we use save_post action, let's check post type here
$post_type = get_post_type($post_id);
if ( "product" != $post_type ) return;

$tag_categories = array (
    'ring' => 'Jewellery'
    'necklace' => 'Jewellery',
    'dress' => 'Clothing',
);

// get_terms returns ALL terms, so we have to add object_ids param to get terms to a specific product
$product_tags = get_terms( array( 'taxonomy' => 'product_tag', 'object_ids' => $product_id ) );
foreach ($product_tags as $term) {
    if ($tag_categories[$term->slug] ) {
        $cat = get_term_by( 'name', $tag_categories[$term->slug], 'product_cat' );
        $cat_id = $cat->term_id;
        if ($cat_id) {
            $result =  wp_set_post_terms( $product_id, $cat_id, 'product_cat', true );
        }
    }
}
}
add_action('save_post','auto_add_category');

披露:我正在建立一个 WordPress 网站并边走边学。这可能是一个显而易见的问题,但请放心,经过数小时的研究以尝试回答我自己(这一切都很好,我在研究时学到了其他东西......只是不是正确的东西!)。非常感谢您提供任何精通见解。

4

1 回答 1

1

此代码放置在您的functions.php文件中时将检查产品的交付选项,然后将相应的类别分配给产品。如果该产品的任何产品类别已经存在,它会将它们附加到列表中。产品类别首先需要存在,如果存在,那么它会为该类别分配与交付选项相同的 slug。我使用钩子save_post_product以便它仅在更新产品时触发。

add_action('save_post_product', 'update_product_category', 20, 3);

function update_product_category( $post_id, $post, $update ) {
    $product = wc_get_product( $post_id );
    $delivery_methods = array( 'pick-up', 'postal', 'post', 'parcel' );

    $delivery_option = get_post_meta($post_id, 'delivery_option', true);

    if( ! empty( $delivery_option ) ) {
        $product_cats = $product->get_category_ids();

        foreach( $delivery_methods as $delivery_method) {
            if( $delivery_option === $delivery_method ) {
                $pickup_cat_id = get_term_by('slug', $delivery_method, 'product_cat')->term_id;

                if( $pickup_cat_id && ! in_array( $pickup_cat_id, $product_cats) ) {
                    $product_cats[] = $pickup_cat_id;
                    $product->set_category_ids($product_cats);
                    $product->save();
                }
            }
        }
    }
}
于 2018-04-03T06:53:11.550 回答