Добавляйте категории продуктов WooCommerce к продуктам вместо перезаписи

Я пытаюсь заставить woocommerce добавлять категории продуктов вместо перезаписи при загрузке новых категорий через csv.

Я попытался найти фрагменты кода. Искал код и попытался использовать wp-includes/post.php для создания функции.

function wp_set_post_terms( $post_id = 0, $tags = '', $taxonomy = 'post_tag', $append = true ) {
    $post_id = (int) $post_id;

    if ( ! $post_id ) {
        return true;
    }

    if ( empty( $tags ) ) {
        $tags = array();
    }

    if ( ! is_array( $tags ) ) {
        $comma = _x( ',', 'tag delimiter' );
        if ( ',' !== $comma ) {
            $tags = str_replace( $comma, ',', $tags );
        }
        $tags = explode( ',', trim( $tags, " \n\t\r\0\x0B," ) );
    }

    if ( is_taxonomy_hierarchical( $taxonomy ) ) {
        $tags = array_unique( array_map( 'intval', $tags ) );
    }

    return wp_set_object_terms( $post_id, $tags, $taxonomy, $append );
}

Я ожидаю, что категории продуктов woocommerce будут добавлены, а не перезаписаны.

фактический результат

фатальная ошибка в строке 29: невозможно повторно объявить wp_set_post_terms() (ранее объявлено в /var/www/html/wp-includes/post.php:4108)

попробовал этот код. нет ошибок, но не добавляет категории

function append_post_categories( $post_ID = array(), $post_categories = array(), $append = true ) {
    $post_ID     = (int) $post_ID;
    $post_type   = get_post_type( $post_ID );
    $post_status = get_post_status( $post_ID );
    // If $post_categories isn't already an array, make it one:
    $post_categories = (array) $post_categories;
    if ( empty( $post_categories ) ) {
        if ( 'post' == $post_type && 'auto-draft' != $post_status ) {
            $post_categories = array( get_option( 'default_category' ) );
            $append          = true;
        } else {
            $post_categories = array();
        }
    } elseif ( 1 == count( $post_categories ) && '' == reset( $post_categories ) ) {
        return true;
    }

    return wp_set_post_terms( $post_ID, $post_categories, 'category', $append );
}

person ucarman    schedule 20.04.2019    source источник


Ответы (1)


Тип сообщения для продуктов WooCommerce — product, но не post, а таксономия для «категории продукта» — не category, а product_cat, поскольку это пользовательская таксономия для пользовательского типа сообщения product

Итак, если вы хотите использовать свою функцию для категории продуктов WooCommerce для продуктов, попробуйте следующее:

function append_product_categories( $product_id, $term_ids, $append = true ) {
    $product_id  = (int) $product_id;
    $post_type   = get_post_type( $product_id );
    $post_status = get_post_status( $product_id );
    $term_ids    = (array) $term_ids;

    if ( empty( $term_ids ) ) {
        if ( 'product' == $post_type && 'auto-draft' != $post_status ) {
            $term_ids = array( get_option( 'default_product_cat' ) );
            $append   = true;
        } else {
            $term_ids = array();
        }
    } elseif ( 1 == count( $term_ids ) && '' == reset( $term_ids ) ) {
        return true;
    }

    // Check for existing term id in the product | Check if term exist in Woocommerce
    foreach( $term_ids as $key => $term_id ) {
        if( hast_term( $term_id, 'product_cat', $product_id ) || ! term_exists( $term_id, 'product_cat' ) ) {
            unset($term_ids[$key]); // remove term id from the array
        }
    }

    return wp_set_post_terms( $product_id, $term_ids, 'product_cat', $append );
}

Он должен лучше работать для категорий продуктов WooCommerce (непроверено)

person LoicTheAztec    schedule 21.04.2019
comment
Спасибо LoicTheAztec, только что проверил это. нет ошибок. но все еще перезаписывает категории. не добавляет. - person ucarman; 21.04.2019