在woocommerce中创建一个带有音频文件的可下载产品

时间:2015-02-19 09:19:22

标签: php wordpress upload woocommerce attachment

相信你的一天已经充实。我需要从前端创建一个可下载的woocommerce产品。我已经能够创建发布产品的链接并添加音频文件作为附件,但我需要在付款后下载此附件,就像您从仪表板发布可下载的woocommerce产品一样。我已经可以在仪表板中看到我的产品,但我必须手动检查可下载并从仪表板添加文件。我需要帮助,以便我可以自动从前端下载产品。 永远感谢别人。 以下是我的代码段。

// ADD THE FORM INPUT TO $new_post ARRAY
    $new_post = array(
    'post_title'    =>   $title,
    'post_content'  =>   $description,
    'post_category' =>   array($_POST['cat']),  
    'tags_input'    =>   array($tags),
    'post_status'   =>   'draft',          
    'post_type' =>   'product',  //'post',page' or use a custom post type if you want to
    'rating'    =>   $myrating
    );

//SAVE THE POST
$pid = wp_insert_post($new_post);

         //KEEPS OUR COMMA SEPARATED TAGS AS INDIVIDUAL
wp_set_post_tags($pid, $_POST['post_tags']);

//REDIRECT TO THE NEW POST ON SAVE
$link = get_permalink( $pid );
wp_redirect( $link );

//ADD OUR CUSTOM FIELDS
add_post_meta($pid, 'rating', $myrating, true);

//INSERT OUR MEDIA ATTACHMENTS
if ($_FILES) {
    foreach ($_FILES as $file => $array) {
    $newupload = insert_attachment($file,$pid);
    // $newupload returns the attachment id of the file that

    }

} // END THE IF STATEMENT FOR FILES

1 个答案:

答案 0 :(得分:0)

你应该做的是,在你的functions.php中添加这段代码。

function user_downloads($order_id) {
// Variables to change
$download_file_id = CUSTOM_ID_OR_ATTACHMENT_ID_OF_FILE;
$user_id = USER_ID;
$product_id = PRODUCT_ID;


  $order = new WC_Order( $order_id );
  if($order['product_id'] == $product_id ){

    $user_downloads = get_user_meta($user_id, 'user_downloads', TRUE);
    if(!empty($user_downloads)){
        $user_downloads = $user_downloads.','.$download_file_id;
        update_user_meta($user_id, 'user_downloads', $user_downloads );
    }else{
        update_user_meta($user_id, 'user_downloads', $user_downloads );
    }
  }
}
add_action( 'woocommerce_order_status_completed', 'user_downloads' );

此代码将挂钩到woocommerce,当订单完成时,它将创建一个新的用户元数据。因此,每个为指定产品付款的用户都会有一个名为' user_downloads'的新元数据。此项的值将是附件ID或某些加密ID的逗号分隔值。现在您在模板页面中所要做的就是

$user_downloads = get_user_meta($user_id, 'user_downloads', TRUE);
$user_downloads = explode(',',$user_downloads);

foreach($user_downloads as $user_download){
   echo '<a href="'.wp_get_attachment_url( $user_downloads[$user_download] ).'">Downloadable File</a>';
}

通过这种方式,他们可以购买任意数量的产品,所有这些商品都会堆叠在用户资料中,可以从中下载。