简体   繁体   English

WPDB查询-根据_meta_key返回meta_value

[英]WPDB Query - Return meta_value based on _meta_key

Please could someone help with extending the functionality of this code to incorporate the end date of the event as well as the start? 请有人帮忙扩展此代码的功能,以纳入活动的结束日期和开始日期吗?

<?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>';
  } 

  }
  ?> 

I tried changing 我尝试改变

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

to

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

This then returns the start date and end date meta keys but im not able to echo these values out separately. 然后,这将返回开始日期和结束日期元键,但无法单独回显这些值。

Basically, I would like to output this 基本上,我想输出这个

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

for each event. 对于每个事件。

hope this question is clearer? 希望这个问题更清楚吗?

Thanks 谢谢

[EDIT] [编辑]

The meta keys for the start and end dates are: 开始日期和结束日期的元键是:

_EventStartDate and _EventEndDate both in wp_postmeta _EventStartDate_EventEndDate都在wp_postmeta中

Thanks 谢谢

If you want to get custom post_type post then you can use WP_Query , and to get meta's you have to use get_post_meta() . 如果要获取自定义post_type帖子,则可以使用WP_Query ,而要获取meta的帖子,则必须使用get_post_meta()
Do some this like this: 做这样的事情:

$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;
        //...
    }
}

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM