0

我有一个数组我传递给 wp_insert_post() 中的 tax_input 参数。下面是打印 wp_insert_post() 参数的结果。

[tax_input] => Array
    (
        [knpvsoftcomp] => Array
            (
                [0] => 1530
            )

        [knpvfiletype] => Array
            (
                [0] => 1497
            )

        [product_cat] => Array <-- Woo Product Categories
            (
                [0] => 821
                [1] => 829
                [2] => 1530
                [3] => 908
            )

        [pa_designer] => Array
            (
                [0] => 549
            )

    )

这是插入新帖子的功能。

$newpostargs = [
        'post_type' => 'product',
        'post_title' => sanitize_text_field($this->submission['fieldvalues']['product_title']),
        'post_author' => $this->currentUser->ID,
        'post_content' => $this->submission['fieldvalues']['description'],
        'post_status' => 'draft',
        'tax_input' => $this->knpv_tax_input(),
        'meta_input' => $this->knpv_meta_input()    
    ];
    $newpost = wp_insert_post($newpostargs);

这是被调用来创建分类数组的函数。

public function knpv_tax_input(){

    $taxarray = [];
    $productcategories = [];

    foreach ($this->submission['fieldvalues'] as $key => $value) {

        //For product_categories
        if (strpos($key, 'cat-parent') !== false || strpos($key, 'catchild-') !== false) {
            $productcategories[] = $value;
        }

        //Software version
        if (strpos($key, 'software') !==  false) {
            $taxarray['knpvsoftcomp'] = [$value];
        }

        //File Types
        if (strpos($key, 'file-compat') !== false) {
            $taxarray['knpvfiletype'] = [$value];
        }           

    }

    //Add product categories to tax array
    $productcategories[] = 908;
    $taxarray['product_cat'] = $productcategories;


    //Supplier (Vendor) Taxonomy
    $taxarray['pa_designer'] = [$this->submission['vendor']['vendor_id']];

    return $taxarray;

}

所有这些都是 Woo 产品类别的自定义分类法。但是,这些是分配给该职位的唯一术语。有什么想法吗?

我是网站的管理员,所以所有权限都设置正确。

4

1 回答 1

1

将 '$term_id' 替换为您的术语 ID 希望这对您有所帮助。

// Creates woocommerce product 
$product = array(
    'post_title'    => $name,
    'post_content'  => '',
    'post_status'   => 'publish',
    'post_author'   => $current_user->ID,
    'post_type'     =>'product'
);

// Insert the post into the database
$product_ID = wp_insert_post($product);
wp_set_object_terms($product_ID, $term_id, 'product_cat')

;

//you-want-multiple-cat

$categories = [ 'Some Category', 'Some other Category' ];
// Overwrite any existing term
wp_set_object_terms( $product_id, $categories, 'product_cat' );

// Or, set last argument to true to append to existing terms
wp_set_object_terms( $product_id, $categories, 'product_cat', true );
于 2020-02-25T06:21:15.483 回答