您只需将产品的post ID与订单一起存储(最简单的方法是通过post_meta
). 然后你可以运行WP_query
去拿所有的产品。
下面的示例是一个授予用户访问自定义帖子类型和收费积分的系统,并提供更新时发送电子邮件、设置访问状态和手动收费积分的选项。
虽然它和你的不太一样,但同样的原则正在发挥作用。
我假设您已经可以使用WordPress挂钩、CPTs元数据库等。
您需要:
将产品添加到表单(使用ajax搜索和获取产品ID)
钩住update_post
将表单保存到post_meta
列出来自post_meta
在页面上假设您有一个具有以下形式的元盒:
<form>
<?php
// lets get all your products saved as a serialized list
// more on how thats done later
$product_ids = get_post_meta( $post_id, \'product_ids\', true );
// if no value, set default empty array
if ( empty( $product_ids ) ) {
$product_ids = array();
} else {
// otherwise, deserialize the value
$product_ids = explode( $product_ids, \',\' );
}
/*
Two things to note about this code:
1. We are saving the IDs as a string, with ids separated by \',\'
which we explode into an array to use
2. We are using the post_meta \'single\' argument instead of
saving multiple metas and retrieving as array.
You could do save multitple meta values, but it will use up more of
your database and is generally harder to maintain
*/
?>
<table id="product_list">
<?php foreach( $product_ids as $p_id ) : ?>
<tr>
<td><input type="text" name="product_id[]" value="<?php echo $p_id; ?>"></td>
</tr>
<?php endforeach; ?>
<!--
- Each row has an input with the same name ( id[] )
- Each input value must be a valid ID
You have to use javascript to populate this table with new items
which can be fetched using ajax through an input elsewhere in the page
Note that to remove a field, just remove it from the DOM
When saving, we\'ll overwrite the whole array, so any missing
items won\'t be saved ... as if they were never there!
-->
</table>
</form>
你可以加入
save_post
.
$_POST[ \'product_id\' ]
现在有一个包含所有帖子ID的数组。方便的
function yourdomain_save_post( $post_id ) {
// check we are updating your product CPT
if ( get_post_type( $post_id ) != \'your_products_cpt\' ) { return; }
// Parse the product id
// make sure to check the values receieved, nonces, sanitization etc!
$product_ids = join( $_POST[ \'product_id\' ], \',\' );
// this will serialize your product IDs: "2,34,92,3"
// So it can be used with the display code in the previous example
// save the list
update_post_meta( $post_id, \'product_ids\', $product_ids, true );
}
现在,如果要提取每个产品信息(说出其名称),可以使用
WP_Query
:
// get comma separated string with product IDs
$product_ids = get_post_meta( $post_id, \'product_ids\', true );
// create WP_Query
$args = array(
\'post_type\' => \'your_products_cpt\',
\'post__in\' => $product_ids // you can use a comma separated list
// of IDs here ... coincidence..?
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
// pretty standard loop from now on
// You\'re a pro at this I am sure!
}
真的是这样!
我知道这有点匆忙,但希望这足以让你开始。
一旦这些项目就绪,您就可以开始添加更好的功能和UX,例如使用jQuery ui autocomplete和Ajax来搜索产品名称,在表中使用名称(ID为隐藏字段),显示产品图片。。。天空是极限。
如果您想快速完成,请查看ACF relationship fields.
还要花一些时间在药典中查找代谢箱和save post hooks
对于Ajax,我总是指excelent article on Smashingmag
请记住检查您的ID,清理输入并使用nonce保护您的站点!
干杯