简体   繁体   中英

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

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() .
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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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