Wpdb查询内的联接..糊涂了!

时间:2011-06-24 作者:MartinJJ

我需要从提供电子邮件、用户名或昵称以及基于作者id的文章标题的查询中获得返回。

该查询将通过cron每天运行一次,并查找在删除之前已使用了特定生存时间的帖子(该查询将在帖子删除之前运行五天,然后运行三天)。

到目前为止,我通过在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)  
在这里一切都很好,它返回了成功,但是我现在需要得到的也是所有到期的帖子的post\\u标题,以便可以将其添加到wp\\u邮件的$message部分中。

老实说,我对加入stuff一无所知。无论它是否需要左连接、外部连接或任何其他类型的连接,我似乎从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
}
?>
完整工作代码below 对于任何感兴趣的人:

<?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>\' . "\\r\\n";


$headers .= "From: -------- <www.------------.com>" . "\\r\\n";


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

}


?>  
上面的代码将在720小时后通知作者,在自动删除帖子之前,他们还有3天的时间。

当做

1 个回复
最合适的回答,由SO网友:TheDeadMedic 整理而成
$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;
}
结束

相关推荐

在小部件中使用$wpdb对象

我试图制作一个非常简单的小部件,它可以访问与Wordpress数据库相同的数据库实例中包含的表,但不是Wordpress表。我正在使用wpdb class according to the codex. 我没有得到任何错误,但我也没有得到任何结果。我是否正确使用了对象?还是应该为自己的表滚动自己的访问类?以下是小部件代码:function widget ($args,$instance) { extract($args); global