Using WordPress ‘get_date_sql’ PHP filter

The get_date_sql WordPress PHP filter allows you to modify the date query WHERE clause.

Usage

add_filter('get_date_sql', 'my_custom_function', 10, 2);
function my_custom_function($where, $query) {
    // your custom code here
    return $where;
}

Parameters

  • $where (string): WHERE clause of the date query.
  • $query (WP_Date_Query): The WP_Date_Query instance.

More information

See WordPress Developer Resources: get_date_sql

Examples

Filter posts from a specific date range

To show only posts from a specific date range, you can use the following code:

add_filter('get_date_sql', 'filter_posts_by_date_range', 10, 2);
function filter_posts_by_date_range($where, $query) {
    global $wpdb;
    $start_date = '2023-01-01';
    $end_date = '2023-01-31';
    $where .= $wpdb->prepare(" AND post_date >= %s AND post_date <= %s", $start_date, $end_date);
    return $where;
}

Exclude posts older than a specific date

To exclude posts older than a specific date, you can use the following code:

add_filter('get_date_sql', 'exclude_old_posts', 10, 2);
function exclude_old_posts($where, $query) {
    global $wpdb;
    $date_limit = '2023-01-01';
    $where .= $wpdb->prepare(" AND post_date >= %s", $date_limit);
    return $where;
}

Filter posts by a specific day of the week

To show only posts published on a specific day of the week, you can use the following code:

add_filter('get_date_sql', 'filter_posts_by_day_of_week', 10, 2);
function filter_posts_by_day_of_week($where, $query) {
    global $wpdb;
    $day_of_week = 5; // Friday
    $where .= $wpdb->prepare(" AND DAYOFWEEK(post_date) = %d", $day_of_week);
    return $where;
}

Show only posts from the current month

To show only posts from the current month, you can use the following code:

add_filter('get_date_sql', 'filter_posts_by_current_month', 10, 2);
function filter_posts_by_current_month($where, $query) {
    global $wpdb;
    $current_month = date('Y-m');
    $where .= $wpdb->prepare(" AND DATE_FORMAT(post_date, '%%Y-%%m') = %s", $current_month);
    return $where;
}

Filter posts by custom date field

To filter posts based on a custom date field, you can use the following code:

add_filter('get_date_sql', 'filter_posts_by_custom_date_field', 10, 2);
function filter_posts_by_custom_date_field($where, $query) {
    global $wpdb;
    $start_date = '2023-01-01';
    $end_date = '2023-01-31';
    $where .= $wpdb->prepare(" AND meta_key = 'event_date' AND meta_value >= %s AND meta_value <= %s", $start_date, $end_date);
    return $where;
}