Проблема с пользовательскими таксономиями при использовании wp_insert_post () - PullRequest
0 голосов
/ 24 февраля 2020

У меня есть массив, который я передаю в аргумент tax_input в wp_insert_post (). Ниже приведен результат печати аргументов 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. Тем не менее, это единственные условия, назначаемые на должность. Любые мысли?

Я администратор на сайте, поэтому все разрешения установлены правильно.

1 Ответ

1 голос
/ 25 февраля 2020

Замените '$ term_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 );
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...