diff --git a/mailpoet/lib/Segments/WooCommerce.php b/mailpoet/lib/Segments/WooCommerce.php index dc63bf311f..8ed543d9ad 100644 --- a/mailpoet/lib/Segments/WooCommerce.php +++ b/mailpoet/lib/Segments/WooCommerce.php @@ -338,18 +338,43 @@ class WooCommerce { } $subscribersTable = $this->entityManager->getClassMetadata(SubscriberEntity::class)->getTableName(); - $metaKeys = [ - '_billing_first_name', - '_billing_last_name', - ]; - $metaData = $this->connection->executeQuery(" - SELECT post_id, meta_key, meta_value - FROM {$wpdb->postmeta} - WHERE meta_key IN (:metaKeys) AND post_id IN (:postIds) - ", - ['metaKeys' => $metaKeys, 'postIds' => array_values($orders)], - ['metaKeys' => Connection::PARAM_STR_ARRAY, 'postIds' => Connection::PARAM_INT_ARRAY] - )->fetchAllAssociative(); + if ($this->woocommerceHelper->isWooCommerceCustomOrdersTableEnabled()) { + $addressesTableName = $this->woocommerceHelper->getAddressesTableName(); + $metaData = []; + $results = $this->connection->executeQuery(" + SELECT order_id, first_name, last_name + FROM {$addressesTableName} + WHERE order_id IN (:orderIds) and address_type = 'billing'", + ['orderIds' => array_values($orders)], + ['orderIds' => Connection::PARAM_INT_ARRAY] + )->fetchAllAssociative(); + + // format data in the same format that is used when querying wp_postmeta (see below). + foreach ($results as $result) { + $firstNameData['post_id'] = $result['order_id']; + $firstNameData['meta_key'] = '_billing_first_name'; + $firstNameData['meta_value'] = $result['first_name']; + $metaData[] = $firstNameData; + + $lastNameData['post_id'] = $result['order_id']; + $lastNameData['meta_key'] = '_billing_last_name'; + $lastNameData['meta_value'] = $result['last_name']; + $metaData[] = $lastNameData; + } + } else { + $metaKeys = [ + '_billing_first_name', + '_billing_last_name', + ]; + $metaData = $this->connection->executeQuery(" + SELECT post_id, meta_key, meta_value + FROM {$wpdb->postmeta} + WHERE meta_key IN ('_billing_first_name', '_billing_last_name') AND post_id IN (:postIds) + ", + ['metaKeys' => $metaKeys, 'postIds' => array_values($orders)], + ['metaKeys' => Connection::PARAM_STR_ARRAY, 'postIds' => Connection::PARAM_INT_ARRAY] + )->fetchAllAssociative(); + } $subscribersData = []; foreach ($orders as $email => $postId) {