I have some php running in a WordPress page, which runs a MySQL query to get transaction details from custom post meta. It’s complicated, so I’ll start with a bit of background:
Custom post type “transaction” is for incoming money. The meta of interest is a date and an amount.
Custom post type “payment” is for outgoing money. Again, the meta of interest is a date and an amount (which is always negative, just to make calculations easier).
Each transaction/payment is a published post. The SQL I’m running gets a list of all the pertinent info for a user’s balance sheet:
(SELECT a.post_type, a.ID, a.post_title, b.meta_value as date, c.meta_value as amount
FROM $wpdb->posts a, $wpdb->postmeta b, $wpdb->postmeta c
WHERE a.ID = b.post_ID
AND a.ID = c.post_ID
AND a.post_author = $user_id
AND a.post_status = 'publish'
AND a.post_type = 'transaction'
AND b.meta_key = '_txn_date'
AND c.meta_key = '_txn_amount')
UNION
(SELECT a.post_type, a.ID, a.post_title, b.meta_value as date, c.meta_value as amount
FROM $wpdb->posts a, $wpdb->postmeta b, $wpdb->postmeta c
WHERE a.ID = b.post_ID
AND a.ID = c.post_ID
AND a.post_author = $user_id
AND a.post_status = 'publish'
AND a.post_type = 'payment'
AND b.meta_key = '_payment_date'
AND c.meta_key = '_payment_amount')
ORDER BY date DESC
Then I take those results and calculate the balance:
$items = $wpdb->get_results($transact);
$total_balance = 0;
foreach ($items as $item) {
$item_amount = $item->amount;
$total_balance += $item_amount;
}
Then I want to loop through all the results and show each one in a line of a table.
foreach ($items as $item) {
$id = $item->ID;
$item_date = date('d M Y', strtotime($item->date));
$item_type = $item->post_type;
$item_amount = number_format($item->amount,2);
$item_name = $item->post_title;
if ($item_type = 'transaction') {
$item_site_id = get_post_meta($id, '_txn_site_id', true);
$item_name = get_the_title($item_site_id);
}
echo '<tr><td>' . $item_date . '</td>
<td>' . $item_name . '</td>
<td align="right">' . $item_amount . '</td></tr>';
}
echo '</table>';
}
The weirdness is in the output: I’ve looked at the results and the query is fine. The extra “if” loop for transactions (which goes off and gets the site name from another custom post type) works fine. But the $item_name for payments comes up with the current page name, not the payment’s post title.
For example, in the raw results, the post_title says “Payout: 02 Feb 2014”, but it shows as “My Balance” in the output table.
I suspect this is because of some kind of bizarre php loop stuff. Can anyone see why?