Skip to content

Instantly share code, notes, and snippets.

@csaborio001
Created March 9, 2021 02:11
Show Gist options
  • Save csaborio001/f7c9a1e6d8cb4677691fb93d22036a8b to your computer and use it in GitHub Desktop.
Save csaborio001/f7c9a1e6d8cb4677691fb93d22036a8b to your computer and use it in GitHub Desktop.
Modifying Repeater Query from Oxygen for a Particular Custom Post Type
<?php
/**
* Modifies event listing.
*
* @package scorpiotek-wordpress-utilities
*
*/
namespace ScorpioTek\WPUtil\Events;
class EventQueryMod {
private $custom_post_type_name;
public function __construct( $custom_post_type_name ) {
$this->custom_post_type_name = $custom_post_type_name;
add_action(
'pre_get_posts',
array( $this, 'go_loco' )
);
}
public function go_loco( $query ) {
if ( empty( $this->custom_post_type_name ) ) {
return $query;
}
/** This will work for regular post archives. */
$post_condition = $query->is_post_type_archive( $this->custom_post_type_name );
/** This will work for Oxygen queries. */
if ( ! $query->is_main_query() && ! empty( $query->query['post_type'][0] ) && 'sb_event' === $query->query['post_type'][0] ) {
$post_condition = true;
}
if ( ! $post_condition ) {
return $query;
}
// Avoids infinite loop.
\remove_action( 'pre_get_posts', array( $this, 'go_loco' ) );
$events_per_page = get_field( 'events_to_display', 'options' );
$events_sort_order = get_field( 'event_sort_order', 'options' );
$events_archives_per_page = get_field( 'event_archives_to_display', 'options' );
$events_archives_sort_order = get_field( 'event_archive_sort_order', 'options' );
\add_action( 'pre_get_posts', array( $this, 'go_loco' ) );
if ( ! is_admin() ) {
$date_now = ( new \DateTime( 'now', \wp_timezone() ) )->format( 'Ymd' );
/** Default to upcoming events. */
$compare = '>=';
if ( isset( $_GET['archive'] ) && 'true' === $_GET['archive'] ) {
/** We need to get everything older than today. */
$compare = '<';
$events_per_page = $events_archives_per_page;
$events_sort_order = $events_archives_sort_order;
}
$query->set( 'posts_per_page', $events_per_page );
$query->set( 'meta_key', 'datepicker_event_start_date' );
$query->set( 'orderby', 'meta_value' );
$query->set( 'order', $events_sort_order );
$query->set(
'meta_query',
array(
array(
'key' => 'datepicker_event_start_date',
'value' => $date_now,
'compare' => $compare,
),
)
);
}
return $query;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment