我有为Student post\\u类型保存元数据的代码。在保存元数据的同时,我还想为payments数组中的每个付款添加单独的帖子:
add_action( \'save_post\', \'save_student_meta\' );
function save_student_meta( $post_id ) {
// Code gathering data form $_POST
// [...]
$student_id = $post_id;
$meta_key = \'_student_name\';
$meta_value = $student_name,
update_post_meta( $student_id, $meta_key, $meta_value );
// For each payment add Payments post into database
foreach( $student_payments as $payment ) {
$postarr = array(
\'post_title\'=>\'empty\',
\'post_content\'=>\'empty\',
\'post_type\'=>\'payments\',
\'post_status\'=>\'publish\',
\'meta_input\'=>array(
\'_payment_date\'=>$payment[\'date\'],
\'_payment_amount\'=>$payment[\'amount\'],
\'_payment_status\'=>$payment[\'status\'],
\'_payment_student_id\'=>$student_id
)
);
wp_insert_post( $postarr, true );
}
}
问题是,在数据库中,每个付款的帖子都有学生的元数据:
付款后元:
- \'\'u payment\\u date\'
- \'\'u payment\\u amount\'
- \'\'u payment\\u status\'
- \'\'u payment\\u student\\u id\'
- \'\'u student\\u name\'<- should not be saved with Payment post这里可能有什么问题?
最合适的回答,由SO网友:ManzoorWani 整理而成
原因是save_post
环当你打电话的时候wp_insert_post
, 它触发save_post
从而插入学生元。
您可以做的是,在插入meta时检查post类型是否正确。
例如:
add_action( \'save_post\', \'save_student_meta\', 10, 2 );
function save_student_meta( $post_id, $post ) {
if ( \'student\' !== $post->post_type ) {
return;
}
// Code gathering data form $_POST