Join inside a wpdb query.. confused!

I need to get a return from a query that provides me with email, username or nicename as well as post title based on author id.

The query is to run once daily via cron and look for posts that have spent a specific live time before they come up for removal (the query is intended to run five days and then three days before post deletion).

Read More

so far i have this which works (almost) via running manual queries in phpmyadmin.

SELECT ID, user_email, display_name, user_nicename
FROM wp_users
WHERE ID
IN (SELECT post_author FROM wp_posts WHERE post_type = 'sales' AND HOUR( TIMEDIFF( NOW( ) , post_date_gmt ) ) >=1)  

alls well and good here, it returns success however what i now need to get is also the post_titles of all the posts due for expiry so that it can be added inside the $message part of the wp_mail.

Im going to be honest with you i havent a clue about joining stuff. whether it needs left joins, outside joins or any other kind of join there maybe, the only info i seem to keep getting back from codex is this page

Update

<?php
$emailusers = $wpdb->get_results("SELECT ID, user_email FROM $wpdb->users WHERE ID IN (SELECT post_author FROM $wpdb->posts WHERE post_type = 'sales' AND HOUR( TIMEDIFF( NOW( ) , post_date_gmt ) ) >=1)");

foreach ($emailusers as $user) {
// do wp_mail stuff from here
}
?>

Full working code below for anyone who is interested:

<?php 
require_once 'wp-load.php';

global $wpdb;

$emailusers = $wpdb->get_results("SELECT u.user_nicename, u.user_email, p.post_title,  p.post_date
FROM $wpdb->posts p
INNER JOIN $wpdb->users u ON p.post_author = u.ID
WHERE post_type = 'sales' OR post_type = 'rentals' OR post_type = 'business'
AND HOUR( TIMEDIFF( NOW( ) , post_date_gmt ) ) >=721");


foreach ($emailusers as $user) {

$to = $user->user_email;

$subject = $user->post_title;

$message = 'You have a property listing that will auto expire in 3 days, the property is <strong>' . $user->post_title .'</strong> and was listed on <strong>' . $user->post_date .'</strong>' . "rn";


$headers .= "From: -------- <www.------------.com>" . "rn";


wp_mail( $user_email, $subject, $message, $headers);

}


?>  

The code up above will notify the author @ 720 hours that they have 3 days remaining before the post is auto deleted.

regards

Related posts

Leave a Reply

1 comment

  1. $emailusers = $wpdb->get_results(
        "SELECT p.ID AS post_id, p.post-title, u.user_email " .
        "FROM $wpdb->posts AS p " .
        "INNER JOIN $wpdb->users AS u ON p.post_author = u.ID " .
        "WHERE p.post_type = 'sales' AND HOUR( TIMEDIFF( NOW( ) , p.post_date_gmt ) ) >=1)"
    );
    
    foreach ($emailusers as $user) {
        // do wp_mail stuff from here
    
        // $emailusers->post_title;
        // $emailusers->user_email;
    
        // used 'post_id' alias rather than 'ID' so it's clear it's not the author ID
        // $emailusers->post_id;
    }