Include custom table in query

时间:2015-08-06 作者:th3rion

Im使用事件日历插件,我可以设置帖子的事件日期,并显示在日历小部件中。一切都很顺利,但我也想按活动日期查询帖子。

问题是事件日期存储在名为wp_ftcalendar_events. 元密钥的名称为start_datetime. 表以post ID开头,所以它是两个表共享的。不幸的是,加入表格超出了我的知识范围。

enter image description here

我的尝试无效:

        <?php
        global $wpdb;
        $date = date("Y-m-d");
             $querystr = "
                SELECT $wpdb->posts.* 
                FROM $wpdb->posts, $wpdb->wp_ftcalendar_events
                WHERE $wpdb->posts.post_parent = $wpdb->wp_ftcalendar_events.post_parent 
                AND $wpdb->posts.post_status = \'publish\' 
                AND $wpdb->wp_ftcalendar_events.meta_key = \'start_datetime\' 
                AND $wpdb->wp_ftcalendar_events.meta_value > " . $date . " 
                ORDER BY $wpdb->wp_ftcalendar_events.meta_value ASC
             ";


             $pageposts = $wpdb->get_results($querystr, OBJECT);
             foreach ($pageposts as $post): ?>          

        <!-- do stuff -->

        <?php endforeach; ?>

1 个回复
最合适的回答,由SO网友:th3rion 整理而成

Working code:

<?php
global $wpdb;
$date = date("Y-m-d");
$querystr = "
SELECT * 
FROM wp_posts
JOIN wp_ftcalendar_events ON wp_posts.ID = wp_ftcalendar_events.post_parent
WHERE wp_posts.post_status =  \'publish\'
AND wp_posts.post_type =  \'post\'
AND wp_ftcalendar_events.start_datetime >= \'$date\' 
ORDER BY wp_ftcalendar_events.start_datetime ASC 
 ";
 $pageposts = $wpdb->get_results($querystr, OBJECT_K); ?>
 <?php if ($pageposts): ?>

  <?php global $post; ?>
  <?php foreach ($pageposts as $post): ?>
      <?php setup_postdata($post); ?>

      <?php $start_date = date_i18n("Y-m-d", strtotime( $post->start_datetime )); ?>

      <?php the_title(); ?><br>
      <?php echo $date; ?><br>
      <?php echo $start_date; ?><br>
  <?php endforeach; ?>

 <?php endif; ?>
结束