以编程方式将可下载文件添加到 Woocommerce 产品

Add programmatically a downloadable file to Woocommerce products

在我的解决方案中,我希望尽可能自动化产品创建。 在我看来,一种节省时间的方法是将可下载文件自动添加到产品中。

我创建了这个函数:

function fcsp_add_downloadable_file($post_id, $post, $update){
  $post_thumbnail_id = get_post_thumbnail_id( $post_id );
  $url = get_site_url()."/wp-content/uploads/".get_the_date('Y')."/".get_the_date('m')."/".$filename_only = basename( get_attached_file( $post_thumbnail_id ) );

  update_post_meta($post_id, '_downloadable_files' , $url);
}
add_action( 'save_post', 'fcsp_add_downloadable_file', 99, 3 );

我可以在更新产品时看到文件路径已保存到 _downloadable_files 元键。然而,它只是纯文本,而不是 woocommerce 存储它的方式。查看屏幕截图(这是使用 Woo 添加产品界面创建的另一个产品:

它也不被 woocommerca 识别为可下载文件。非常感谢任何解决此问题的帮助。

编辑:第二部分

这是要设置的产品标题:

我们必须从图像的 EXIF 元标记 "title" 中获取它,并且必须在保存产品之前或同时将其设置为产品名称。 ($filemeta['image_meta']['title'];)

更新 2 (添加了一个 if 语句以允许下载生成 只生成一个文件

The following code will auto add a downloadable file made from the product image (The download title comes from the EXIF data title).

你最好使用专用的 woocommerce_admin_process_product_object 动作挂钩和可用的 CRUD objects and getters / setters methods 以这种方式在 woocommerce 3 中引入:

add_action( 'woocommerce_admin_process_product_object', 'auto_add_downloadable_file', 50, 1 );
function auto_add_downloadable_file( $product ){
    // Get downloads (if there is any)
    $downloads = (array) $product->get_downloads(); 

    // Only added once (avoiding repetitions
    if( sizeof($downloads) == 0 ){
        // Get post thumbnail data
        $thumb_id = get_post_thumbnail_id( $product->get_id() );
        $src_img  = wp_get_attachment_image_src( $thumb_id, 'full');
        $img_meta = wp_get_attachment_metadata( $thumb_id, false );

        // Prepare download data
        $file_title = $img_meta['image_meta']['title'];
        $file_url   = reset($src_img);
        $file_md5   = md5($file_url);

        $download  = new WC_Product_Download(); // Get an instance of the WC_Product_Download Object

        // Set the download data
        $download->set_name($file_title);
        $download->set_id($file_md5);
        $download->set_file($file_url);


        $downloads[$md5_num] = $download; // Insert the new download to the array of downloads

        $product->set_downloads($downloads); // Set new array of downloads
    }
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。已测试并有效。

You could also check if product is downloadable using is_downloadable() method in an IF statement on start inside the function.