Skip to content

Instantly share code, notes, and snippets.

@jo-snips
Last active January 5, 2023 17:24
Show Gist options
  • Star 30 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save jo-snips/5112025 to your computer and use it in GitHub Desktop.
Save jo-snips/5112025 to your computer and use it in GitHub Desktop.
The Events Calendar - Custom Query Using WP_Query
<?php
$args = array(
'post_status'=>'publish',
'post_type'=>array(TribeEvents::POSTTYPE),
'posts_per_page'=>10,
//order by startdate from newest to oldest
'meta_key'=>'_EventStartDate',
'orderby'=>'_EventStartDate',
'order'=>'DESC',
//required in 3.x
'eventDisplay'=>'custom',
//query events by category
'tax_query' => array(
array(
'taxonomy' => 'tribe_events_cat',
'field' => 'slug',
'terms' => 'featured',
'operator' => 'IN'
),
)
);
$get_posts = null;
$get_posts = new WP_Query();
$get_posts->query($args);
if($get_posts->have_posts()) : while($get_posts->have_posts()) : $get_posts->the_post(); ?>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a><br />
<?php if (tribe_get_start_date() !== tribe_get_end_date() ) { ?>
<?php echo tribe_get_start_date(); ?> - <?php echo tribe_get_end_date(); ?>
<?php } else { ?>
<?php echo tribe_get_start_date(); ?>
<?php } ?>
<?php the_content(); ?>
<?php
endwhile;
endif;
wp_reset_query();
?>
@kimipooh
Copy link

kimipooh commented Dec 3, 2013

I think that wp_reset_postdata(); is better than wp_reset_query(); because the get_posts() type should be used in this case.

$get_posts = new WP_Query($args);
....
wp_reset_postdata();

@jacquesletesson
Copy link

wp_reset_postdata() cause you are using a custom WP_Query()

You right. More information here : https://wordpress.stackexchange.com/questions/144343/wp-reset-postdata-or-wp-reset-query-after-a-custom-loop

@airton
Copy link

airton commented Oct 2, 2017

Great, thanks!

I needed to use a different date format so I used it so:

<?php echo tribe_get_start_date(null, false, 'd'); ?> for day
<?php echo tribe_get_start_date(null, false, 'M'); ?> for month name

@dynostudios
Copy link

How could we use this query, but show all dates even if the date is empty? Working on a Tribe Event custom carousel but want to show all dates (Start date to End date).

@munts
Copy link

munts commented Jan 7, 2021

It looks like 'TribeEvents' in line 5 is deprecated and we should be using 'Tribe__Events__Main'. I just ran into this issue and have had to update all of my custom events queries. This is a change since version 3.10 and when I made my change, it caused me date formatting issues with tribe_get_start_date(). Just thought I would share. Also, to get the correct date format, I followed Airton's example and used:
$month = tribe_get_start_date ( $post->ID, false, 'M');
$day = tribe_get_start_date ( $post->ID, false, 'j');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment