1 回答

TA貢獻1844條經驗 獲得超8個贊
對于自定義的 meta_keys 列表(company、firstname、address),您可以定義一個包含這些的數組,并將它們作為尾隨列添加到 CSV 中,如下所示:
global $wpdb;
// Define your custom meta keys you want to add as columns HERE:
$meta_keys = ['company', 'firstname', `address`]; // can contain as many as you want
// This function will load the desired keys as an associative array
// in the form: [$meta_key_1 => $meta_value_1, ..., $meta_key_n => $meta_value_n]
function load_user_meta($user_id, $keys) {
$meta_row = [];
foreach ($keys as $meta_key) {
$value = get_user_meta($user_id, $meta_key, true);
$meta_row[$meta_key] = $value;
}
return $meta_row;
}
$table_name = $wpdb->prefix . 'users';
$results = $wpdb->get_results("SELECT * FROM $table_name", ARRAY_A);
if (empty($results)) {
return;
}
// Merge the result's keys with the list of custom meta keys:
$csv_output = '"'.implode('";"',array_merge(array_keys($results[0]), $meta_keys )).'";'."\n";
foreach ($results as $row) {
// load the custom meta for this user's ID:
$custom_meta_row = load_user_meta($row['ID'], $meta_keys);
// merge the acquired user meta into the row output:
$csv_output .= '"'.implode('";"',array_merge($row, $custom_meta_row)).'";'."\n";
}
$csv_output .= "\n";
如果meta_key并非所有用戶都存在某個特定的情況,這仍然有效,因為get_user_meta將為這些情況生成一個空字符串。
附加說明:按照您的方式生成 CSV 輸出通常不是一個好主意。只要你的任何地方都沒有"and;字符,這種方法就有效user_meta- 這些字符必須使用特定的轉義字符進行轉義。因此,最好fputcsv在輸出流( $outstream = fopen("php://output", 'w');)上使用。
- 1 回答
- 0 關注
- 181 瀏覽
添加回答
舉報