我正在从包含大量信息和品牌列的 csv 中导入 woocommerce 产品。我成功添加了所有信息(描述、价格、属性和条款,但我无法成功添加品牌信息。我的代码如下。 第一个函数 insert_products 是我写的,其余函数是我在互联网上找到的,经过一些修改,我设法使它们工作。
function insert_products()
{
global $wpdb;
$rows = $_POST['productFound']; // contain my data in array format.
foreach ($rows as $row) {
$meta_array = array(
'_regular_price' => $row[15], //price display
'_price' => $row[15], //price display
'_product_cost_price' => $row[17], //price cost
'_product_call_for_price'=>$row[20], //call for price
'_sku' => $row[3], //part no
'_product_retail_msrp_price' => $row[14], //price list
'_weight' => $row[11], //Weight
'free_ship' => $row[22], //Free Ship
'upc' => $row[5], //upc
'spec_url' => $row[32], //Spec_Url
// 'shipped_from_zip' => $row[21], //shiped from zip
't_keywords' => $row[30], //keywords
);
$my_post = array(
'post_title' => $row[4], //Title
'post_content' => $row[29], //Long description
'post_type' => 'product',
'post_excerpt' => $row[28], //Short description
'post_category' => $row[1], //Category
'meta_input' => $meta_array,
);
$insertedProduct = wp_insert_post($my_post, true);
if (is_wp_error($insertedProduct)) {
$errors = $insertedProduct->get_error_messages();
foreach ($errors as $error) {
echo "- " . $error . "<br />";
}
} else {
//,"Shipping Price" => array($row[23]),"Shipping Height" => array($row[24]),"Shipping Length" => array($row[25]),"Shipping Width" => array($row[26]),"Shipping Weight" => array($row[27])
//"Brand" => array($row[2]),
wp_set_post_terms( $insertedProduct, $row[2], 'product_brand', true ); //For Brand inserting
// Inserting attributes. Got this code from internet and with few small changes this works good for me.
$yourRawAttributeList = array($heading[2]=>array($row[2]),$heading[7] => array($row[7]),
$heading[8] => array($row[8]),$heading[9] => array($row[9]),[10] => array($row[10]),
$heading[11] => array($row[11]),"Status" => array($row[12]),"Status" => array($row[12]),"Free Ship" => array($row[22]),"Display" => array($row[36]),"Lumens" => array($row[37]),"Native Aspect Ratio" => array($row[38]),"Native Resolution" => array($row[39]),"Contrast" => array($row[40]),"Supported Resolution" => array($row[41]),"Supported Spectratios" => array($row[42]),"Thorw Ratio" => array($row[43]),"Zoom" => array($row[44]),"Ioconnectors" => array($row[45]),"Built In Speaker" => array($row[46]),"Projector Lens" => array($row[47]),"Light Source" => array($row[49]),"Accessories" => array($row[50]),"3D" => array($row[51]),"Case Color" => array($row[52]),"Diagonal" => array($row[53]),"Frame Width" => array($row[54]),"Gain" => array($row[55]),"Rear" => array($row[56]),"Screen Type" => array($row[57]),"Supported Aspect Ratio" => array($row[58]),"Surface" => array($row[59]),"Tension" => array($row[60]),"View Height" => array($row[61]),"View Width" => array($row[62]),"Color" => array($row[63]),"Fixed" => array($row[64]),"In Wall" => array($row[65]),"Load Capacity" => array($row[66]),"Mounting Points" => array($row[67]),"Pivot" => array($row[68]),"Pole Color" => array($row[69]),"Rotate" => array($row[70]),"Swivel" => array($row[71]),"Tilt" => array($row[72]),"Vesa" => array($row[73]),"Weight Capacity" => array($row[74]),"Cable Length" => array($row[75]),"Cable Connector 1" => array($row[76]),"Cable Connector 2" => array($row[77]),"Plenum" => array($row[78]),"Shielded" => array($row[79]));
$attribs = $this->generate_attributes_list_for_product($yourRawAttributeList);
$p = new WC_Product($insertedProduct);
$p->set_props(array(
'attributes' => $attribs,
//Set any other properties of the product here you want - price, name, etc.
));
$postID = $p->save();
if ($postID <= 0) return "Unable to create / update product!";
//Attribute Terms: These need to be set otherwise the attributes dont show on the admin backend:
foreach ($attribs as $attrib)
{
/** @var WC_Product_Attribute $attrib */
$tax = $attrib->get_name();
$vals = $attrib->get_options();
$termsToAdd = array();
if (is_array($vals) && count($vals) > 0)
{
foreach ($vals as $val)
{
if(!$val) continue;
echo $val."<br>";
//Get or create the term if it doesnt exist:
$term = $this->get_attribute_term($val, $tax);
if ($term['id']) $termsToAdd[] = $term['id'];
}
}
if (count($termsToAdd) > 0)
{
print_r($termsToAdd);
//wp_set_object_terms($postID, $termsToAdd, $tax, true);
}
}
}
}
}
以下是我在互联网上找到的功能,它们可以工作。
function create_global_attribute($name, $slug)
{
$taxonomy_name = wc_attribute_taxonomy_name( $slug );
if (taxonomy_exists($taxonomy_name))
{
return wc_attribute_taxonomy_id_by_name($slug);
}
//logg("Creating a new Taxonomy! `".$taxonomy_name."` with name/label `".$name."` and slug `".$slug.'`');
$attribute_id = wc_create_attribute( array(
'name' => $name,
'slug' => $slug,
'type' => 'select',
'order_by' => 'menu_order',
'has_archives' => false,
) );
//Register it as a wordpress taxonomy for just this session. Later on this will be loaded from the woocommerce taxonomy table.
register_taxonomy(
$taxonomy_name,
apply_filters( 'woocommerce_taxonomy_objects_' . $taxonomy_name, array( 'product' ) ),
apply_filters( 'woocommerce_taxonomy_args_' . $taxonomy_name, array(
'labels' => array(
'name' => $name,
),
'hierarchical' => true,
'show_ui' => false,
'query_var' => true,
'rewrite' => false,
) )
);
//Clear caches
delete_transient( 'wc_attribute_taxonomies' );
return $attribute_id;
}
//$rawDataAttributes must be in the form of array("Color"=>array("blue", "red"), "Size"=>array(12,13,14),... etc.)
function generate_attributes_list_for_product($rawDataAttributes)
{
$attributes = array();
$pos = 0;
foreach ($rawDataAttributes as $name => $values)
{
if (empty($name) || empty($values) || $values[0]=="" || $values[0]=="0") continue;
if (!is_array($values)) $values = array($values);
$attribute = new WC_Product_Attribute();
$attribute->set_id( 0 );
$attribute->set_position($pos);
$attribute->set_visible( true );
//$attribute->set_variation( true );
$pos++;
//Look for existing attribute:
$existingTaxes = wc_get_attribute_taxonomies();
//attribute_labels is in the format: array("slug" => "label / name")
$attribute_labels = wp_list_pluck( $existingTaxes, 'attribute_label', 'attribute_name' );
$slug = array_search( $name, $attribute_labels, true );
if (!$slug)
{
//Not found, so create it:
$slug = wc_sanitize_taxonomy_name($name);
$attribute_id = $this->create_global_attribute($name, $slug);
}
else
{
//Otherwise find it's ID
//Taxonomies are in the format: array("slug" => 12, "slug" => 14)
$taxonomies = wp_list_pluck($existingTaxes, 'attribute_id', 'attribute_name');
if (!isset($taxonomies[$slug]))
{
//logg("Could not get wc attribute ID for attribute ".$name. " (slug: ".$slug.") which should have existed!");
continue;
}
$attribute_id = (int)$taxonomies[$slug];
}
$taxonomy_name = wc_attribute_taxonomy_name($slug);
$attribute->set_id( $attribute_id );
$attribute->set_name( $taxonomy_name );
$attribute->set_options($values);
$attributes[] = $attribute;
}
return $attributes;
}
function get_attribute_term($value, $taxonomy)
{
//Look if there is already a term for this attribute?
$term = get_term_by('name', $value, $taxonomy);
if (!$term)
{
//No, create new term.
$term = wp_insert_term($value, $taxonomy);
if (is_wp_error($term))
{
//logg("Unable to create new attribute term for ".$value." in tax ".$taxonomy."! ".$term->get_error_message());
return array('id'=>false, 'slug'=>false);
}
$termId = $term['term_id'];
$term_slug = get_term($termId, $taxonomy)->slug; // Get the term slug
}
else
{
//Yes, grab it's id and slug
$termId = $term->term_id;
$term_slug = $term->slug;
}
return array('id'=>$termId, 'slug'=>$term_slug);
}