如果客户购买了特定产品,如何获取该产品的订单ID?我尝试了下面的代码,但是没有用。感谢您的提前帮助。
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const passport = require('passport');
const path = require('path');
//Route files
const users = require('./routes/api/users');
const fpsos = require('./routes/api/fpsos');
const bids = require('./routes/api/bids');
const news = require('./routes/api/news');
const app = express();
//Body parser middlewares
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json ());
//DB config
const db = require('./config/keys').mongoURI;
//Connect to MongoDB
mongoose
.connect(db)
.then(() => console.log('MongoDB connected'))
.catch(err => console.log(err));
//Passport middleware
app.use(passport.initialize());
//Passport Config
require('./config/passport')(passport);
app.use('/api/users', users);
app.use('/api/news', news);
app.use('/api/fpso', fpsos);
app.use('/api/bid', bids);
// Server static assets if in production
if (process.env.NODE_ENV === 'production') {
// Set static folder
app.use(express.static('client/build'));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
});
}
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server running on port ${port}`))
也尝试过此代码,但是没有用。
<?php
$order = new wc_get_order( $order_id );
$order->get_id();
echo $order->get_order_number();
?>
答案 0 :(得分:1)
function get_order_ids_from_bought_items() {
$prod_arr = array('37', '53');
$purchased = false;
$customer_orders = get_posts(array(
'numberposts' => -1,
'post_type' => 'shop_order',
'meta_key' => '_customer_user',
'meta_value' => get_current_user_id(),
));
foreach ($customer_orders as $order_post) {
$order = wc_get_order($order_post->ID);
foreach ($order->get_items() as $item) {
$product_id = $item->get_product_id();
if (in_array($product_id, $prod_arr))
$purchased = true;
}
}
return $purchased; // $order_post->ID for Order ID
}
答案 1 :(得分:1)
以下函数使用非常轻量级的SQL查询,该查询将返回给定客户的已定义产品ID的最后一个订单ID:
function get_last_order_id_from_product( $product_id, $user_id = 0 ) {
global $wpdb;
$customer_id = $user_id == 0 ? get_current_user_id() : $user_id;
return $wpdb->get_var( "
SELECT p.ID FROM {$wpdb->prefix}posts AS p
INNER JOIN {$wpdb->prefix}postmeta AS pm ON p.ID = pm.post_id
INNER JOIN {$wpdb->prefix}woocommerce_order_items AS woi ON p.ID = woi.order_id
INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS woim ON woi.order_item_id = woim.order_item_id
WHERE p.post_type = 'shop_order'
AND pm.meta_key = '_customer_user'
AND pm.meta_value = $customer_id
AND woim.meta_key IN ( '_product_id', '_variation_id' )
AND woim.meta_value = $product_id
ORDER BY p.ID DESC LIMIT 1
" );
}
代码在您的活动子主题(或活动主题)的function.php文件上。经过测试,可以正常工作。
如果客户尚未购买产品,该功能将返回
false
。
用法示例:
在下面,您将设置产品ID 37
,还可以设置用户ID 153
(如果您不要在函数可以获取当前用户ID的前端使用代码* /
$order_id = get_last_order_id_from_product( 37, 153 );
或对于当前用户:
$order_id = get_last_order_id_from_product( 37 );