WPDB查询 - 基于_meta_key

时间:2017-01-25 12:08:48

标签: php mysql wordpress datetime

请有人帮忙扩展此代码的功能,以包含事件的结束日期和开始日期吗?

<?php
  global $wpdb;
  $result = $wpdb->get_results ( "SELECT $wpdb->posts.ID, $wpdb->posts.post_content, $wpdb->postmeta.meta_id, $wpdb->postmeta.post_id, $wpdb->postmeta.meta_key, $wpdb->postmeta.meta_value, $wpdb->posts.post_title FROM $wpdb->posts INNER JOIN $wpdb->postmeta ON $wpdb->posts.ID = $wpdb->postmeta.post_id WHERE $wpdb->postmeta.meta_key = '_EventStartDate' ORDER BY $wpdb->postmeta.meta_value " );


  foreach ( $result as $page ) {
  $date = new DateTime($page->meta_value);

  if (strtotime($page->meta_value) >= strtotime('monday this week') && strtotime($page->meta_value) < strtotime('monday next week')) {
  echo '<h2><div class="date-title">';
  echo $page->post_title;
  echo '</div><div class="date-date">';
  echo $date->format('d-m-Y').'<br/>';
  echo '</div></h2>';
  } 

  }
  ?> 

我尝试过更改

WHERE $wpdb->postmeta.meta_key = '_EventStartDate'

WHERE $wpdb->postmeta.meta_key = '_EventStartDate' OR $wpdb->postmeta.meta_key = '_EventEndDate'

然后返回开始日期和结束日期元键,但我无法单独回显这些值。

基本上,我想输出这个

Event Name starts on (start date here) and finishes on (end date here)

每个活动。

希望这个问题更清楚吗?

由于

[编辑]

开始和结束日期的元键是:

wp_postmeta

中的

_EventStartDate_EventEndDate

由于

1 个答案:

答案 0 :(得分:0)

如果您想获得自定义的post_type帖子,那么您可以使用WP_Query,要获取元素,您必须使用get_post_meta()
做这样的事情:

$args = array(
    'post_type' => array('event'), //<-- Replace it with your custom post_type
    'post_status' => array('publish'),
    'order' => 'DESC',
    'orderby' => 'date'
);

// The Query
$query = new WP_Query($args);
if (!empty($query->posts))
{
    foreach ($query->posts as $post)
    {
        $_EventStartDate = get_post_meta($post->ID, '_EventStartDate', TRUE);
        $_EventEndDate = get_post_meta($post->ID, '_EventEndDate', TRUE);
        echo $post->post_title . ' starts on ' . $_EventStartDate . ' and finishes on ' . $_EventEndDate;
        //...
    }
}

希望这有帮助!