WooCommerce/Wp All Import 如果要上传的产品名称已经存在于数据库中,则跳过安装

分享于2022年07月17日 php woocommerce wpallimport 问答
【问题标题】:WooCommerce/Wp All Import 如果要上传的产品名称已经存在于数据库中,则跳过安装(WooCommerce/Wp All Import If the product name to be uploaded already exists in the database, skip the installation)
【发布时间】:2022-06-21 05:20:19
【问题描述】:

如果产品名称已存在于数据库中,我希望它跳过产品上传。我有这样的代码,但是这样上传不启动,报错。

 add_filter( 'wp_all_import_is_post_to_create', 'my_is_post_to_create', 10, 3 );
  function my_is_post_to_create( $continue_import, $data, $import_id ) {
     global $product;
     $product = wc_get_product(get_the_ID());
     $current_title = $product->get_name();
     $new_title = $data['name'];
     if ( $import_id == 34 ) {
        if ( $new_title == $current_title ) {
            return false;
        }
    }
    return true;
} 


【解决方案1】:

如果有人需要,这是我找到的解决方案。

add_filter('wp_all_import_is_post_to_create', 'create_only_if_unique_custom_field', 10, 3);
function create_only_if_unique_custom_field( $continue_import, $data, $import_id ) { 
    // Only run for import ID 33 and 34
    if ( $import_id == 33 ) {
    
    // Xml file column name
    $value = $data['name'];
        
    // Get wpdb product title
  $posts = get_posts([
    'post_type'  => 'product',
    'title' => $value,  
  ]);
    
    return !$posts;

    } else {
       // Take no action if a different import ID is running.
       return $continue_import;
    }
}